grep -v and regex

How to match lines that don't contain a patern in regex it self, without using the -v option of grep?

More details, please! If you post sample input and example of the expected output.
... and, why "without using -v"?

You are saying to negate insite the regex? Like:

'[^abc]'

It means, not abc.

The obvious solution to matching lines that don't match a regular expression without resorting to grep -v would be to not use grep at all.

sed -n '/regexp/!p'

I realize that my response could be construed as sarcasm, but it's not.

Why is grep's -v unavailable? Does the implementation not provide it? If not, which platform are you on? I'm always curious about these situations.

Regards,
Alister

after all... what is 'grep'? And why is it called 'grep'? 'grep' is a glorified sed: sed 'g/re/p'.

Actually a glorified ed :slight_smile:

Except in that all three use regular expressions, I don't really see the relation... ed's capabilities are very different from both.

It's also horrifying. :smiley:

1 Like

LOL!:b:

Sample text:

aaaaa
bbbbb
ccccc
ddddd

I want to list all lines except "bbbbb". So I can use "grep -v bbbbb". But I want to express the meaning of "lines except a patern" using regex itself, not any option of any command. Is it possible that regex can't express negative meaning? Why must use a outside -v or sed's '!p' command?

PS: [^patern] is not the one I want. It just negative of chars in [], not the patern string!

Something like this may work:

perl -ne'
  /^(?!b{5}$)/ and  print
  ' infile

GNU grep:

grep -P '^(?!b{5}$)' infile
1 Like

No, no, no.... That line not really bbbb. I just take it as an example. The lines may be any strings.

grep -P '^(?!whateverregexforyourline$)' infile

can work for any line, not just b*5.

Exactly :slight_smile:

grep -P '^(?!whateverregexforyourline$)' infile

That does'nt work...

As always, sample input and actual vs. expected output is needed ...

Tom Christiansen & Nathan Torkington's "Perl Cookbook" explains this in the chapter on "Pattern Matching", section "Expressing AND, OR, and NOT in a Single Pattern" (I have the first edition, � 1998, which describes it on pages 198 and 200.)

From page 198:

True if pattern /PAT/ does not match, like $var !~ /PAT/:
    /^(?:(?!PAT).)*$/s

A detailed example is given on page 200:

$map =~ /^(?:(?!waldo).)*$/s

Spelled out in long form, this yields:
if ($map =~ m{
        ^                  # start of string
        (?:                # non-capturing grouper
            (?!            # look ahead negation
                waldo      # is he ahead of us now?
            )              # if so, the negation failed
            .              # any character (cuzza /s)
        )*                 # repeat that grouping 0 or more times
        $                  # through the end of the string
    }sx )                  # /s means . can match newline
{
    print "There's no waldo here!\n";
}