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

Viewed 59

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"

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 
3 Answers

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)

In order to match an entire line you need to match the start and end of the line:

grep '^abc$' file.txt
grep '^abc-def$' file.txt

You can use awk this way:

awk -v w="abc" '$1==w' file.txt
abc

Or,

awk '$1==w' w="abc" file.txt

With the == operator, it only returns exact string matches. We are setting what to match with w="abc" either with the -v switch or through stdin.

Related