我有两个文件.File1如下
Apple
Cat
Bat
Run Code Online (Sandbox Code Playgroud)
File2如下
I have an Apple
Batman returns
This is a test file.
Run Code Online (Sandbox Code Playgroud)
现在我想检查第一个文件中哪些字符串不在第二个文件中.我可以做一个,grep -f file1 file2但那给了我第二个文件中匹配的行.
要获取第一个文件和第二个文件中的字符串:
grep -of file1 file2
Run Code Online (Sandbox Code Playgroud)
结果(使用给定的示例)将是:
Apple
Bat
Run Code Online (Sandbox Code Playgroud)
要获取第一个文件中但不在第二个文件中的字符串,您可以:
grep -of file1 file2 | cat - file1 | sort | uniq -u
Run Code Online (Sandbox Code Playgroud)
甚至更简单(感谢@ triplee的评论):
grep -of file1 file2 | grep -vxFf - file1
Run Code Online (Sandbox Code Playgroud)
结果(使用给定的示例)将是:
Cat
Run Code Online (Sandbox Code Playgroud)
从grep 手册页:
-o, - only-matching
仅打印匹配行的匹配(非空)部分,每个此类部分位于单独的输出行上.
从uniq 手册页:
-u, - unique
仅打印唯一的行