Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grep for the whole word

Tags:

grep

unix

I am using the following command to grep stuff in subdirs

find . | xargs grep -s 's:text' 

However, this also finds stuff like <s:textfield name="sdfsf"...../>

What can I do to avoid that so it just finds stuff like <s:text name="sdfsdf"/>

OR for that matter....also finds <s:text somethingElse="lkjkj" name="lkkj"

basically s:text and name should be on same line....

like image 586
josh Avatar asked May 21 '10 01:05

josh


People also ask

Which flag to grep causes it to search for whole words?

Checking for the whole words in a file : By default, grep matches the given string/pattern even if it is found as a substring in a file. The -w option to grep makes it match only the whole words.

How do I grep exact match?

grep exact match with -w From the man page of grep: -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character.


Video Answer


2 Answers

You want the -w option to specify that it's the end of a word.

find . | xargs grep -sw 's:text'

like image 175
Elle H Avatar answered Sep 23 '22 15:09

Elle H


Use \b to match on "word boundaries", which will make your search match on whole words only.

So your grep would look something like

grep -r "\bSTRING\b" 

adding color and line numbers might help too

grep --color -rn "\bSTRING\b" 

From http://www.regular-expressions.info/wordboundaries.html:

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.
like image 22
cs01 Avatar answered Sep 21 '22 15:09

cs01