grep with logic operators
There are lot of ways to use grep
with logical operators.
Use
\|
to separate multiple patterns for the OR condition.Example:
grep 'pattern1\|pattern2' filename
Use the
-E
option to send multiple patterns for the OR condition.Example:
grep -E 'pattern1|pattern2' filename
Using a single
-e
matches only one pattern, but using multiple-e
option matches more than one pattern.Example:
grep -e pattern1 -e pattern2 filename
grep -v
can simulate the NOT operation.There is no AND operator in
grep
, but you can brute-force simulate AND by using the-E
option.Example :
grep -E 'pattern1.*pattern2|pattern2.*pattern1' filename
The above example will match all the lines that contain both pattern1 and pattern2 in either order.)
With awk
, as with perl
, you'll have to wrap terms in //
, but it can be done:
awk '(/term1/ && /term2/) || (/term1/ && xor(/term3/, /term4/))'
You could use perl:
perl -wne 'print if (/term1/ && /term2/) || (/term1/ && (/term3/ xor /term4/))'
Where the switches are as follows:
-w turns on warnings
-n runs perl against each line of input (looping)
-e executes perl passed in the command line