I have two files. File1 is as follows
Apple
Cat
Bat
以下是File2的内容
I have an Apple
Batman returns
This is a test file.
现在我想检查第一个文件中哪些字符串不在第二个文件中。我可以执行
grep -f file1 file2
,但这只会给出第二个文件中匹配的行。grep -of file1 file2
Apple
Bat
grep -of file1 file2 | cat - file1 | sort | uniq -u
grep -of file1 file2 | grep -vxFf - file1
Cat
来自grep
命令的手册页:
-o, --only-matching
只打印匹配行中已匹配(非空)的部分,在单独的输出行中打印每个该样的部分。
来自uniq
命令的手册页:
-u, --unique
仅打印唯一的行。
grep -of file1 file2 | grep -vxFf - file1
。 - tripleeewhile read word
do
grep -q "$word" f2 || echo "$word"
done < f1
为了匹配精确的单词,请添加-w
: grep -wq
...
$ while read word; do grep -q "$word" f2 || echo "$word"; done < f1
Cat
$ while read word; do grep -wq "$word" f2 || echo "$word"; done < f1
Cat
Bat
$ awk 'FNR==NR {a[$1]; next} {for (i=1;i<=NF;i++) {if ($i in a) delete a[$i]}} END {for (i in a) print i}' f1 f2
Cat
Bat
这将文件file1中的值存储到数组a[]
中。然后,它循环遍历file2的所有行,检查每个单独的元素。如果其中一个与数组a[]
中的值匹配,则将该元素从数组中删除。最后,在END{}
块中打印未找到的值。