Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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

share|improve this question

3 Answers 3

up vote 4 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

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

You can execute

command | grep 'John Smith' | grep -v 'Mr John Smith'
share|improve this answer

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.