如果grep不匹配,则打印输入的搜索字符串
我有文件 1
BOB
JOHN
SALLY
我有文件 2
There was a boy called JOHN and he was playing with FRED while
JILL went off to find a bucket of water from TOM but she
fell down the hill.
我想遍历 file1 单词并在 file2 中搜索这些单词。
我想打印在 file2 中找不到的单词。
所以输出将是
BOB
SALLY
我想如果 grep 失败,我想打印 grep 正在搜索的字符串。
我从这里开始:
grep -o -f file1 file2
但当然,这会返回
JOHN
我将如何获得不匹配的原始搜索字符串 - 改为打印?
回答
这是grep完成此操作的单衬纸:
grep -vxFf <(tr '[[:blank:]]' 'n' < file2) file1
BOB
SALLY
使用tr先将空格/制表符转换为换行符,然后使用grep -vxFf在file1.
或者正如大卫在下面的评论中所建议的那样:
grep -vxFf <(printf '%sn' $(<file2)) file1
- `grep -vxFf <(printf "%sn" $(< file2)) file1` Shorter `:)`
- Okay, that rocks. I thought down the line of process substitution, but couldn't pull it off. `tr` was the key. Good form.
回答
使用您展示的样品,您可以尝试以下操作。
awk '
FNR==NR{
arr[$0]
next
}
{
for(i in arr){
if(index($0,i)){
delete arr[i]
next
}
}
}
END{
for(i in arr){
print i
}
}
' file1 file2