Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to search exact phrase from a file which consist of set of phrase with hyphen

I have the file, which consists of a couple of phrases as follows. I would like to grep the exact match from out of them.

file.txt

abc
abc-def
xyz
xyz-pqr
pqrs

If I search "abc" I need to return only abc.
or
if I search "abc-def" i need to return only "abc-def"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

preferd output

$grep -w "abc" file.txt
abc

or

$grep -w "abc-def" file.txt
abc-def

the below method is not working for the hyphens

$grep -w abc file.txt 

>Solution :

With your given data/file you can use the -x flag.

grep -x abc file.txt

grep -x abc-def file.txt

  • -x, –line-regexp force PATTERN to match only whole lines

  • The -x flag is defined/required by POSIX grep(1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading