bash 打印一个文件中不包含在另一个文件中的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5812756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print lines from one file that are not contained in another file
提问by j.lee
I wish to print lines that are in one file but not in another file. However, neither files are sorted, and I need to retain the original order in both files.
我希望打印在一个文件中但不在另一个文件中的行。但是,两个文件都没有排序,我需要保留两个文件中的原始顺序。
contents of file1:
string2
string1
string3
contents of file2:
string3
string1
Output:
string2
Is there a simple script that I can accomplish this in?
是否有一个简单的脚本可以完成此操作?
回答by Charles Brunet
fgrep -x -f file2 -v file1
-x match whole line
-x 匹配整行
-f FILE takes patterns from FILE
-f FILE 从 FILE 中获取模式
-v inverts results (show non-matching)
-v 反转结果(显示不匹配)
回答by ysth
In Perl, load file2 into a hash, then read through file1, outputing only lines that weren't in file2:
在 Perl 中,将 file2 加载到散列中,然后读取 file1,仅输出不在 file2 中的行:
use strict;
use warnings;
my %file2;
open my $file2, '<', 'file2' or die "Couldn't open file2: $!";
while ( my $line = <$file2> ) {
++$file2{$line};
}
open my $file1, '<', 'file1' or die "Couldn't open file1: $!";
while ( my $line = <$file1> ) {
print $line unless $file2{$line};
}
回答by ghostdog74
awk 'FNR==NR{a[##代码##];next} (!(##代码## in a))' file2 file1
回答by David Okwii
comm <(sort a) <(sort b) -3→ Lines in file b that are not in file a
comm <(sort a) <(sort b) -3→ 文件 b 中不在文件 a 中的行

