Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it possible, using grep, to search for instances of John Smith but exclude instances of Mr John Smith?

share|improve this question
up vote 6 down vote accepted

This could be solved using a regular expression with negative lookbehind (which is experimentally supported in grep as pointed out by the comment from arrange):

$ grep -P '(?<!Mr )John Smith' file

Since the support is just experimental, you might want to use perl instead:

$ perl -nle 'print if /(?<!Mr )John Smith/' file
share|improve this answer
It is experimentally supported in grep: echo $string | grep -P '(?<!Mr )John Smith'. – arrange Dec 12 '11 at 19:00
@arrange Indeed. Thanks, I'll update the answer. – jcollado Dec 12 '11 at 20:10
Perfect -- just what I was after. Thanks! – Sam Hastings Dec 13 '11 at 9:09

You can execute

command | grep 'John Smith' | grep -v 'Mr John Smith'
share|improve this answer
Nice idea, but will not work if the line has John Smith Mr John Smith John Smith – Ron Aug 22 '15 at 8:18

To use regular expressions, use ^ and $

grep "^John Smith$"

^ is match from the beginning $ is match from end.

The syntax will vary depending on what you are searching for in what file.

You can use regular expressions with sed, grep, awk ....


bodhi@Ubuntu:~ cat file
Mr John Smith
John Smith

bodhi@Ubuntu:~ grep "^John Smith$" file
John Smith
share|improve this answer
The OP do not ask for the string to be the only thing on its line. – enzotib Dec 13 '11 at 8:08

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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