search a string in a particular column of file and return the line number of the line

Hi All,

Can you please guide me to search a string in a particular column of file and return the line number of the line where it was found using awk. As an example :

abc.txt


7000,john,2,1,0,1,6
7001,elen,2,2,0,1,7
7002,sami,2,3,0,1,6
7003,mike,1,4,0,2,1
8001,nike,1,5,0,1,8
8002,paul,2,6,0,2,7

In above example search in 4th column for value 5 and return line number 5.

I tried below awk but it does not work

awk '/5/ {if ($4=="5") print $0}' abc.txt

Can some one please help

You are almost there...
Try this...

awk -F, '/5/ {if ($4=="5") print FNR}' abc.txt

--ahamed

1 Like

The above solution worked well :slight_smile:


=> awk -F"," '/5/ {if ($4=="5") print FNR}' abcdefg.txt
5

Thank you ahamed.

If the 4rth column of your (coma separated) file is equal to 5 then the line number is printed:

awk -F, '$4==5 {print NR}' yourfile
1 Like