TonyW
TonyW

Reputation: 18875

how to grep exact match?

I have a CSV file that is delimited by comma. I want to select by the second column that has the exact "stringPattern"

I tried:

grep -w "stringPattern"

but it still gets any string that contains the string Pattern.

What's the awk way to do this?

Upvotes: 1

Views: 4234

Answers (4)

Android Control
Android Control

Reputation: 598

A little late to the party, but there is an additional option to grep that could be helpful... :-)

From the grep manpage:

-o, --only-matching
          Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Lets make a small sample file;

$ echo -e "col1,col2,col3\npattern1,pattern2,pattern3" > file.csv

Now lets search for the pattern, with only the -w option

$ grep --color=always -w "pattern2" file.csv
pattern1,pattern2,pattern3

Now lets search for the pattern with the -w and the -o

$ grep --color=always -ow "pattern2" file.csv
pattern2

Now only the exact match is returned. :-)

...but what if the pattern "repeats" on the same line?

Lets update the sample file and repeat the last search;

$ echo -e "col1,col2,col3,col4\npattern1,pattern2,pattern3,pattern2" > file.csv

Now the search returns both results - but on a separate line

$ grep --color=always -ow "pattern2" file.csv
pattern2
pattern2

This may not be what you want. :-/

Upvotes: 1

Endoro
Endoro

Reputation: 37569

grep -E '^[^,]+,stringPattern,' file

Upvotes: 0

unxnut
unxnut

Reputation: 8839

awk -F, '$2 == "stringPattern" < filename

Upvotes: 3

William Pursell
William Pursell

Reputation: 212248

awk '$2=="stringPattern"' FS=,

Note that this is an exact match, not a regex. If you want a regex, you can do:

$2 ~ /stringPattern/

Upvotes: 3

Related Questions