简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM