Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict grep to search only the one column within a CSV file, but to output matching lines in their entirety?

Tags:

grep

csv

How can I use grep to search only one column within a CSV file, but after a match is found, to output the entire line? E.g.:

fish @ eats worms
bear @ eats fish

Searching for fish in column 2 will output: bear @ eats fish.

like image 527
Village Avatar asked Oct 09 '22 03:10

Village


1 Answers

...Use awk...

awk -F@ '{if ($2 ~ /fish/) { print $0; }}' <input file>

To use a shell variable change single quotes to doubles and escape the awk variables (soo awk still sees $2 etc and not the shell's expansion of them.

awk -F@ "{if (\$2 ~ /$find_me/ ) { print \$0; } }" <input_file>
like image 153
John3136 Avatar answered Oct 13 '22 09:10

John3136