How to grep for lines containing either of two words, but not both

grep

I'm trying to use grep to show only lines containing either of the two words, if only one of them appears in the line, but not if they are in the same line.

So far I've tried grep pattern1 | grep pattern2 | ... but didn't get the result I expected.

Best Answer

A tool other than grep is the way to go.

Using perl, for instance, the command would be:

perl -ne 'print if /pattern1/ xor /pattern2/'

perl -ne runs the command given over each line of stdin, which in this case prints the line if it matches /pattern1/ xor /pattern2/, or in other words matches one pattern but not the other (exclusive or).

This works for the pattern in either order, and should have better performance than multiple invocations of grep, and is less typing as well.

Or, even shorter, with awk:

awk 'xor(/pattern1/,/pattern2/)'

or for versions of awk that don't have xor:

awk '/pattern1/+/pattern2/==1`
Related Question