EA00
EA00

Reputation: 633

grep for exact match

I have a file that looks like this:

1   2HE MET 1.8493
1   3HE MET 1.3568
2   H   GLN 6.1731
2   HA  GLN 4.2384
2   2HB GLN 2.2204
2   3HB GLN 1.3062

I use the grep command: grep H file and get all the lines as shown above. I would like to only retrieve the line 2 H GLN 6.1731. I've used grep 'H$'file as well as grep -x H processed_shifts.out but do not get any output with these commands. How could I modify the grep command to only get line 3 as the output?

Upvotes: 0

Views: 7228

Answers (2)

Connor Smith
Connor Smith

Reputation: 301

If you're using GNU grep then you can use the -w or --word-regexp flag, or wrap the regex with word boundaries:

grep '\bH\b'

However, this will be non-portable, since POSIX grep lacks the -w flag and neither basic nor extended regular expressions support word boundaries. So if you wish for the command to be portable then you'll have to do something like

grep ' H '

or otherwise use a more powerful language, like AWK:

awk '$2=="H" { print }'

Upvotes: 2

Nickknack
Nickknack

Reputation: 857

Try using regular expressions with grep. Try using /^H$/ as what you are grepping. This is the regular expression for an exact match on H. the ^ means the string must start with H and the $ means it must end in H. therefore it will match for any string that is just H.

let me know if that works, as I am unable to test my answer at this moment.

Upvotes: 0

Related Questions