Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep backslash in negative lookbehind

Tags:

regex

grep

bash

I want to find the number of occurrences of XXX in my latex document that are not in the form of a command as \XXX. Therefore I am looking for occurrences that are not preceded by a backslash.

I tried the following:

grep -c -e '(?<!\)XXX' test.tex    #result: grep: Unmatched ) or \)
grep -c -e '(?<!\\)XXX' test.tex   #result: 0
grep -c -e "(?<!\\)XXX" test.tex   #result: -bash: !\\: event not found

none of them work as intended. In fact I don't understand the last error message at all.

My test.tex contains only the following lines

%test.tex

XXX

\XXX

So the expected result is 1.

Any ideas?

Ps.: I am working in bash.

like image 751
Simon Avatar asked Jul 27 '12 09:07

Simon


People also ask

Does grep support Lookbehind?

find (both the GNU and BSD variants) do not support lookahead/lookbehind. GNU grep only supports the POSIX basic and extended regular expression variants as well as a couple of others.

What is a negative Lookbehind?

A negative lookbehind assertion asserts true if the pattern inside the lookbehind is not matched.

Can I use Lookbehind regex?

The good news is that you can use lookbehind anywhere in the regex, not only at the start. If you want to find a word not ending with an “s”, you could use \b\w+(? <! s)\b.

Does JavaScript support negative Lookbehind?

Negative lookbehinds seem to be the only answer, but JavaScript doesn't has one. Consider posting the regex as it would look with a negative lookbehind; that may make it easier to respond. @WiktorStribiżew : Look-behinds were added in the 2018 spec. Chrome supports them, but Firefox still hasn't implemented the spec.


Video Answer


2 Answers

Neither standard nor extended regular expressions support the look behind. Use Perl compatible regexes:

grep -P '(?<!\\)xxx' test.tex
like image 58
choroba Avatar answered Oct 19 '22 17:10

choroba


Try to use

grep -P '(?<!\\)\bXXX\b' test.tex
like image 1
Ωmega Avatar answered Oct 19 '22 18:10

Ωmega