Awk - Grep - Match the exact string in a file

Viewed 435

I have a file that looks like this

ON,111111,TEN000812,Super,7483747483,767,Free
ON,262762,BOB747474,SuperMan,4347374,676,Free
ON,454644,FRED84848,Super Man,65757,555,Free

I need to match the values in the fourth column exactly as they are written. So if I am searching for "Super" I need it to return the line with "Super" only.

ON,111111,TEN000812,Super,7483747483,767,Free

Likewise, if I'm looking for "Super Man" I need that exact line returned.

ON,454644,FRED84848,Super Man,65757,555,Free

I have tried using grep, but grep will match all instances that contain Super. So if I do this:

grep -i "Super" file.txt

It returns all lines, because they all contain "Super"

ON,111111,TEN000812,Super,7483747483,767,Free
ON,262762,BOB747474,SuperMan,4347374,676,Free
ON,454644,FRED84848,Super Man,65757,555,Free

I have also tired with awk, and I believe I'm close, but when I do:

awk '$4==Super' file.txt

I still get output like this:

ON,111111,TEN000812,Super,7483747483,767,Free
ON,262762,BOB747474,SuperMan,4347374,676,Free

I have been at this for hours, and any help would be greatly appreciated at this point.

2 Answers

You were close, or I should say very close just put field delimiter as comma in your solution and you are all set.

awk 'BEGIN{FS=","} $4=="Super"' Input_file

Also one more thing in OP's attempt while comparison with 4th field with string value, string should be wrapped in "

OR in case you want to mention value to be compared as an awk variable then try following.

awk -v value="Super" 'BEGIN{FS=","} $4==value' Input_file

You are quite close actually, you can try :

awk -F, '$4=="Super" {print}' file.txt

I find this form easier to grasp. Slightly longer than @RavinderSingh13 though

-F is the field separator, in this case comma
Next you have a condition followed by action
Condition is to check if the fourth field has the string Super
If the string is found, print it

Related