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
CodePudding user response:
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
CodePudding user response:
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 POSIXgrep
(1)