grep backslash in negative lookbehind

Viewed 16948

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.

4 Answers

The grep version on my MacOS Catalina does not even have the -P flag for Perl style regex,


    $ grep --version
    grep (BSD grep) 2.5.1-FreeBSD

So I just rolled my own version of the grep -l command which I needed to get list of files that matched a negative lookahead regex, below is the source code, feel free to adapt to your own needs,

    #!/usr/bin/perl
      
    use strict;
    use warnings;
    
    # Tries to mimic at least partially `grep -l` command, and provides support for look-arounds using Perl regex'
    # Usage: ls <some folder> | grepList.pl <reg-ex>
    # Algorithm:
    # Open each file in the list supplied
    #   Apply regex to each line, as soon as it matches output file name to STDOUT and continue to next file
    #   If EOF file reached, means file did not match, do not print file name, and move on to next file
    # Runtime complexity: O(m * n), where m is number of files and n is the maximum number of lines a file can have
    # Space complexity:   O(1), no intermediary memory storage needed
    
    my $reg_ex = qr/$ARGV[0]/;
    
    while(<STDIN>) {
        chop($_);
        my $file = $_;
        open(IN, $file) || die "Unable to open $file: $!";
        while(<IN>) {
            my $line = $_;
            if ($line =~ /$reg_ex/) {
                print "$file\n";
                last;
            }
        }
    }

Related