1827421 Members
4337 Online
109965 Solutions
New Discussion

Re: grep command ??

 
MikeL_4
Super Advisor

grep command ??

I am using grep command to look through a file for certain entries, like say the word test, but my problem is there are other entries in the file that begin with have test in them that I don't want returned..
ie:

test
test_107
tup_test
etc.....

the grep for tet would return all three entries when I only want the 1st entry returned...

any ways to get around this ??

Thanks
Mike
8 REPLIES 8
Ralph Grothe
Honored Contributor

Re: grep command ??

if you're after an exact match try fgrep or the -F switch of grep (see manpage),
for more involved parsings use Perl (where amongst other things) you can set anchors in form of word boundaries.
Madness, thy name is system administration
Ian Dennison_1
Honored Contributor

Re: grep command ??

To return just lines that have the word 'test' (and only the word 'test'),...

grep "^test$"

^ = anchor to start of line
$ = anchor to end of line

To get complete word test takes a little more effort.

Share and Enjoy! Ian
Building a dumber user
Rodney Hills
Honored Contributor

Re: grep command ??

Try-

grep "^test$" file

^ matches beginning of line
$ matches end of line

HTH

-- Rod Hills
There be dragons...
Ralph Grothe
Honored Contributor

Re: grep command ??

sorry -F alone wouldn't help I suppose,
append a [[:space:]] to you're regex while using egrep or -E switch (which stands for extended grep)
but that said, nothing compares to Perl's regex capabilities
Madness, thy name is system administration
H.Merijn Brand (procura
Honored Contributor

Re: grep command ??

GNU grep knows -w option, which `anchors' the word to search for

# grep -w test file

GNU grep available on http://www.cmve.net/~merijn or https://www.beepz.com/personal/merijn

Enjoy, have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Tom Jackson
Valued Contributor

Re: grep command ??

Hi Mike:

Try this:

grep test filename|head -n 1

Tom
James R. Ferguson
Acclaimed Contributor

Re: grep command ??

Hi Mike:

# grep -E -e " test " -e " test$" -e "^test " -e "^test$"

...would limit the selection to the word "test".

Regards!

...JRF...
Hai Nguyen_1
Honored Contributor

Re: grep command ??

Mike,

Try this:

# grep -x test input_file

Hai