Village
Village

Reputation: 24413

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

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.

Upvotes: 5

Views: 7714

Answers (2)

Village
Village

Reputation: 24413

Using grep:

grep ^.*@.*fish.*$ file.txt

Upvotes: -1

John3136
John3136

Reputation: 29266

...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>

Upvotes: 5

Related Questions