This question already has an answer here:

When I use the grep command, all occurrences of a word are picked up, even if they are part of other words. For example, if I use grep to find occurrences of the word 'the' it will also highlight 'the' in 'theatre'

Is there a way to adapt the grep command so that it only picks up full words, not part of words?

marked as duplicate by dhag, Stephen Kitt, Jeff Schaller, GAD3R, mdpc Mar 3 '17 at 0:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

 -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.  Similarly, it must be either at the  end
              of  the  line  or  followed by a non-word constituent character.
              Word-constituent  characters  are  letters,  digits,   and   the

from man grep

  • 1
    This is the ultimate answer. Otherwise you should go with something like this: searchword='the'; grep -E "^$searchword\s|\s($searchword)\s|\s$searchword$|^$searchword$" textfile.txt – Mostafa Ahangarha Mar 2 '17 at 17:06
  • 2
    @MostafaAhangarha Less than that would do: \<searchword\> – kasperd Mar 2 '17 at 22:40

Also you can use this:

echo "this is the theater" |grep --color '\bthe\b'

For one word is the same with -w.
But if you need to search multiple patterns you can use the \b, otherwise all patterns will be treated as words if -w is in use.

For example :

grep -w -e 'the' -e 'lock'

will highlight the and lock but not keylock /padlock etc.

With \b you can treat each -e pattern differently.

Test it here.


You can test the presence of the beginning (resp. end) of a word with the marker \< (resp. \>).


grep "\<the\>" << .
the cinema
a cinema
the theater
a theater


the cinema
the theater

Not the answer you're looking for? Browse other questions tagged or ask your own question.