Reputation: 3009
I have a text file having some records. I have two patterns to verify and I want to list all lines from the file not containing both pattern. How can I do this using grep
command?
I tried few things using grep -v
but nothing seem to work.
Suppose my text file is as follows.
1. qwerpattern1
yui
2. adspattern2
asd
3. cczxczc
4. jkjkpattern2
adsdapattern1
I want to list lines 1, 2 and 3 only.
Thanks in advance.
Upvotes: 4
Views: 9571
Reputation: 16016
While the standard tools-based answers (awk
, grep
, etc) are generally simpler and more straightforward, for completion if you needed a pure-bash solution, you could do this:
$ while IFS= read -r ln; do [[ $ln =~ pattern1 ]] && [[ $ln =~ pattern2 ]] && continue; printf "%s\n" "$ln"; done < test
1. qwerpattern1yui
2. adspattern2asd
3. cczxczc
$
Upvotes: 0
Reputation: 41460
If you like to try awk
awk '!/pattern1|pattern2/' file
It will not print any lines if it contains any of the patters
You can also expand this:
awk '!/pattern1|pattern2|pattern3|pattern4/' file
Example
cat file
one
two
three
four
one two
two
nine
six two
remove all lines with one
or two
or both of them.
awk '!/one|two/' file
three
four
nine
Upvotes: 3
Reputation: 786291
You can use:
grep -w -v -e "word1" -e "word2" file
OR else using egrep
:
egrep -w -v -e "word1|word2" file
UPDATE: Based on comments, it seems following awk will work better:
awk '!(/pattern1/ && /pattern2/)' file
Upvotes: 11
Reputation: 16016
If I'm keeping up with the comments and edits right, I think this is what you need:
$ grep -E -v 'pattern1.*pattern2|pattern2.*pattern1' test 1. qwerpattern1yui 2. adspattern2asd 3. cczxczc $
Upvotes: 3