Yes,
grep's (and
sed's) "
-e" expressions (including regex combinations) act like OR, not AND.
Think about how it works. Each line is read in in sequence, and compared to all the expressions given. If it matches
any of them, it returns it as output. Then the next line is read.
So no, if the file must contain ALL of the given expressions, then a single
grep can't handle it. You have to use
awk, or another tool like
perl or even shell scripting, that can keep track of what has and hasn't been found as it iterates through the file.
It would generally also take something more complex than a short one-liner as well. Indeed Colucix's offering:
Code:
awk '!(/1.2.3.1/ && /1.2.3.2/ && /1.2.3.4/ && /1.2.3.8/){exit 1}'
...won't really do, as it stands, because the test is checking each
record (i.e. line) at a time for the existence of
all entries, not the entire file as a whole.
It can be made to work, however, if the file is small enough to sit in memory, and you're using a compatible version of
awk (i.e. gnu). Just redefine the record separator to null, which should make it treat the whole file as a single record. In which case I'd probably go with something more like this:
Code:
awk -v RS='' '{ if (/1[.]2[.]3[.]1/ && /1[.]2[.]3[.]2/ && /1[.]2[.]3[.]4/ && /1[.]2[.]3[.]8/ ) { print "all entries found"; exit 0 } else { print "something not found" ; exit 1 }}' infile.txt
The
print commands are optional, of course I just put them there to clearly illustrate the output.
But if the file is too large for the above, you'd have to a more complex run-through of each line in turn, setting a variable for each matched string, say, then testing those for final compliance at the end.
Here's a proof of concept I just whipped up that appears to work, although it could undoubtedly be made much cleaner with a bit of effort.
Code:
awk '/1[.]2[.]3[.]1/ { a=1 } ; /1[.]2[.]3[.]2/ { b=1 } ; /1[.]2[.]3[.]4/ { c=1 } ; /1[.]2[.]3[.]8/ { d=1 } END{ x=a+b+c+d ; if ( x == 4 ){ print "all 4 found" ; exit 0 } else print "something not found" ; exit 1 }' infile.txt