cancel
Showing results for 
Search instead for 
Did you mean: 

grep and whole words

SOLVED
Go to solution
oiram
Regular Advisor

grep and whole words

Hello:

imagine the next file
---------
/test
/test/hello
/testA
---------
I need to make a grep over it to obtain only the first entry(/test). If I use the -w option I get the following
/test
/test/hello

This must be easy but I don??t know how to do it.

Regards.
3 REPLIES
T G Manikandan
Honored Contributor

Re: grep and whole words

you can pipe it to head

like

/tmp/a

---------
/test
/test/hello
/testA
----------

cat /tmp/a|grep test |head -1
Alan Deger
Trusted Contributor

Re: grep and whole words

With what you've shown here you can get the results you want with an end-of-line metacharacter. Your grep command would look like

grep "/test$" myfile

Hope this helps,
ard
Bob_Vance
Esteemed Contributor
Solution

Re: grep and whole words

If you really want to worry about "words" and assume that the word delimeter is white space (tab or blank), then a more complete expression would be:


grep -E '/test$|/test[[:space:]]' /tmp/x


This checks for the word "/test" at the end of line *or* followed by a whitespace char.

E.g., for the file:
# cat /tmp/x
/test
/test one blank
/test 2 blanks
/test tab
/test/hello
/testA

the results are:

# grep -E '/test[[:space:]]|/test$' /tmp/x
/test
/test one blank
/test 2 blanks
/test tab


bv
"The lyf so short, the craft so long to lerne." - Chaucer