Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match specific column with grep command

Tags:

linux

grep

match

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?

like image 679
upendra Avatar asked Dec 09 '14 22:12

upendra


2 Answers

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 :

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

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

$ awk '$2 == 866{print FILENAME":"$0; nextfile}' *
like image 77
Gilles Quenot Avatar answered Oct 22 '22 06:10

Gilles Quenot


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
like image 20
Harry Avatar answered Oct 22 '22 08:10

Harry