upendra
upendra

Reputation: 2189

Match specific column with grep command

I am having trouble matching specific column with 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 lines which has a number 866 in the second column. When i use grep command i am getting all the lines that contains the number that number

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 match specific column with grep command?

Upvotes: 10

Views: 87475

Answers (2)

Harry
Harry

Reputation: 1277

In my case, the field separator is not space but comma. So I would have to add this, otherwise it won't work for me (On ubuntu 18.04.1).

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

Upvotes: 2

Gilles Quénot
Gilles Quénot

Reputation: 184995

Try doing this :

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

No need to add {print}, the default behaviour of awk is to print on a true condition.

with :

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

But can print filenames too & is quite more robust than here :

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

Upvotes: 24

Related Questions