Print unmatched patterns not the unmatched content of file, using grep

Viewed 231

I'm using grep command in bash to find multiple keywords/patterns which did not find a match

For example below command returns the keywords/patterns that matched

grep -oehE '(cat|dog|apple|mango|bat)' temp.txt | sort | uniq

But I'm looking for a command which can do following:

temp.txt contains
This is a dog the best
Dog are the best
doG
dog
My best buddy is dog
Love mango and candy

The output of search I'm looking for is

cat 
apple
bat

The output is the patterns that did not match the data in the file.

I searched for a similar problem and the closest I could find was below post but it deals with the files rather than all on the command line

Similar problem using file

Any help is appreciated.

1 Answers

Using awk you could:

$ awk -v p="cat|dog|apple|mango|bat" '  # search words
BEGIN {                                 # first make hash of the search words
    split(p,t,/\|/)
    for(i in t)
        a[t[i]]
}
{
    for(i=1;i<=NF;i++)                   # for each record and word in the record
        delete a[$i]                     # remove them from the hash
}
END {                                    # in the end
    for(i in a)                          # in order that appears random
        print i                          # output the leftovers
}' temp.txt

and have the output of:

bat
apple
cat

With grep:

$ echo "cat|dog|apple|mango|bat" | tr \| \\n > pats
$ grep -vf temp.txt pats
cat
apple
bat

With grep without involvment of files:

$ echo -e cat\\ndog\\napple\\nmango\\nbat | grep -vf temp
cat
apple
bat

Related