Home > Net >  Shell script find exact string required
Shell script find exact string required

Time:02-18

I have a file with some data, and from that file I am using grep to find the exact string, but the grep command is giving all the records that contains that string.

file test.txt

ABC
ABC-test

what my usecase is, if I search "cat test.txt | grep ABC", I must only get exact entry with "ABC" and not "ABC-test". What is the way to achieve the same. Please confirm

CodePudding user response:

Please use regex

$ cat test.txt
ABC
ABC-test
$ cat test.txt| grep '^ABC$'
ABC

CodePudding user response:

The flag -w makes grep match whole words and -x the whole line. if test.txt contains

ABC
ABC123
ABC 123

then

grep -w ABC test.txt

will return

ABC
ABC 123

and

grep -x ABC test.txt

will return only

ABC
  • Related