Is it possible, using grep, to search for instances of John Smith
but exclude instances of Mr John Smith
?
3 Answers
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
-
It is experimentally supported in grep:
echo $string | grep -P '(?<!Mr )John Smith'
.– arrangeDec 12, 2011 at 19:00 -
You can execute
command | grep 'John Smith' | grep -v 'Mr John Smith'
-
2Nice idea, but will not work if the line has
John Smith Mr John Smith John Smith
– RonAug 22, 2015 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 ....
Example
bodhi@Ubuntu:~ cat file
Mr John Smith
John Smith
John
Smith
bodhi@Ubuntu:~ grep "^John Smith$" file
John Smith
-
2