使用grep打印不匹配的模式,而不是文件的不匹配内容



我在bash中使用grep命令来查找多个没有找到匹配的关键字/模式

例如,下面的命令返回与匹配的关键字/模式

grep-oehE'(猫|狗|苹果|芒果|蝙蝠('temp.txt |排序| uniq

但我正在寻找一个可以执行以下操作的命令:

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

我正在寻找的搜索输出是

cat 
apple
bat

输出的模式与文件中的数据不匹配。

我搜索了一个类似的问题,我能找到的最接近的是下面的帖子,但它处理的是文件,而不是所有的命令行

使用文件时出现类似问题

感谢您的帮助。

使用awk可以:

$ 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

并具有以下输出:

bat
apple
cat

grep:

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

使用grep而不涉及文件:

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

为了好玩,如果你只有单词(所以不处理空格或特殊字符(,而很少(在命令行的限制下(,你可以使用与术语一样多的grep调用来检查

for p in cat dog apple mango bat; do grep -qsw "$p" temp.txt || echo "$p"; done

在这里,如果在文件中找不到每个单词,就会将其回显。

无论如何,awk替代方案更好,因为您不会多次跳过该过程。

这不能保证排序顺序,因此如果需要,您必须手动sort

mawk -v RS='[[:space:]]+' '
{  __[$_]
} END {     FS = "|"
$_ = ___
for (_ = +_; _++ < NF; _++) { 
if ( ! ( $_ in __ ) ) { 
print $_           } } }' ___='cat|dog|apple|mango|bat'          

最新更新