Reputation: 31642
I'm trying to run grep with the following regex:
(?<!key:)(?<!orKey:)(?<!isEqualToString:)\@\"[A-Za-z0-9]*\"
First try:
$ grep -r -n -H -E (?<!key:)(?<!orKey:)(?<!isEqualToString:)\@\"[A-Za-z0-9]*\" ./
-bash: !key: event not found
Ok, so I need to escape the "!"s...
$ grep -r -n -H -E (?<\!key:)(?<\!orKey:)(?<\!isEqualToString:)\@\"[A-Za-z0-9]*\" ./
-bash: syntax error near unexpected token `('
Ok, so I need to escape the "("s...
$ grep -r -n -H -E \(?<\!key:\)\(?<\!orKey:\)\(?<\!isEqualToString:\)\@\"[A-Za-z0-9]*\" ./
-bash: !key:)(?: No such file or directory
Ok, so I need to quote the string?
$ grep -r -n -H -E '\(?<\!key:\)\(?<\!orKey:\)\(?<\!isEqualToString:\)\@\"[A-Za-z0-9]*\"' ./
Returns no results... but I tried a simpler regex which doesn't have the negative-look-behind assertions, and it ran fine... I also used TextWrangler with this regex and it does work, so I can only assume I'm doing something wrong on the command line here.
EDIT:
If I use the -p
option:
$ grep -r -n -H -E -P '\(?<\!key:\)\(?<\!orKey:\)\(?<\!isEqualToString:\)\@\"[A-Za-z0-9]*\"' ./
grep: conflicting matchers specified
An example of file contents which should match:
NSString * foo = @"bar";
An example of file contents which should NOT match:
return [someDictonary objectForKey:@"foo"];
Upvotes: 4
Views: 6158
Reputation: 77095
It works fine, just avoid using conflicting options. -
[jaypal:~/Temp] cat filename
NSString * foo = @"bar";
return [someDictonary objectForKey:@"foo"];
[jaypal:~/Temp] grep -P '(?<!key:)(?<!orKey:)(?<!isEqualToString:)\@\"[A-Za-z0-9]*\"' filename
NSString * foo = @"bar";
Upvotes: 0
Reputation: 27133
'
quoting works perfectly as long as there are no '
in your expression. And you don't have any, so that should be fine.
If you are really paranoid about quoting, put the expression in a file and use grep -f FILENAME
instead, so that it reads the regex from the file.
But the real issue might be that you need to specify grep -P
to explicitly ask for the Perl regular expression support.
Upvotes: 3
Reputation: 56915
At the core of it you need to quote the entire string with ''
. (If you enclose with ""
the !
will give you grief). Then you only need to escape internal '
within your regex (if any).
Also you want -P
(perl) instead of -E
(egrep) regex.
grep -r -n -H -P '(?<!key:)(?<!orKey:)(?<!isEqualToString:)\@\"[A-Za-z0-9]*\"' ./
Upvotes: 5
Reputation: 46965
try using the -P option which will interpret the regex as a perl regex. Also if you provide some example input and output it would help in getting an answer.
Upvotes: 4