Sunday, June 5, 2022

[SOLVED] Match specific column with grep command

Issue

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?


Solution

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}' *


Answered By - Gilles Quenot
Answer Checked By - Dawn Plyler (WPSolving Volunteer)