Simpler Navigation for Servers and Operating Systems - Please Update Your Bookmarks
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
If you have bookmarked forums or discussion boards in Servers and Operating Systems, we suggest you check and update them as needed.
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