Match column with grep command

I'm having trouble matching a specific column with the grep command. I have a test file (test.txt) like this.

Bra001325 835 T 13 c$c$c$c$c$cccccCcc !!!!!68886676 Bra001325 836 C 8 ,,,,,.,, 68886676 Bra001325 841 A 6 ,$,.,,. BJJJJE Bra001325 866 C 2 ,. HJ 

And I want to extract all those rows that have the number 866 in the second column. When I use the grep , I get all the lines containing the number whose number is

 grep "866" test.txt Bra001325 835 T 13 c$c$c$c$c$cccccCcc !!!!!68886676 Bra001325 836 C 8 ,,,,,.,, 68886676 Bra001325 866 C 2 ,. HJ 

How can I map a specific column to a grep command?

+5
source share
2 answers

Try to do this:

 $ awk '$2 == 866' test.txt 

No need to add {print} , awk 's default behavior is to print in true state.

with :

 $ grep -P '^\S+\s+866\b' * 

But can also print file names and is more reliable than here:

 $ awk '$2 == 866{print FILENAME":"$0; nextfile}' * 
+12
source

In my case, the field separator is not a space, but a comma. Therefore, I would have to add this, otherwise it will not work for me (on Ubuntu 18.04.1).

 awk -F ', ' '$2 == 866' test.txt 
0
source

Source: https://habr.com/ru/post/1208695/


All Articles