【发布时间】:2011-08-14 08:11:03
【问题描述】:
我希望打印在一个文件中但不在另一个文件中的行。但是,两个文件都没有排序,我需要在两个文件中保留原始顺序。
contents of file1:
string2
string1
string3
contents of file2:
string3
string1
Output:
string2
是否有一个简单的脚本可以让我完成这项工作?
【问题讨论】:
我希望打印在一个文件中但不在另一个文件中的行。但是,两个文件都没有排序,我需要在两个文件中保留原始顺序。
contents of file1:
string2
string1
string3
contents of file2:
string3
string1
Output:
string2
是否有一个简单的脚本可以让我完成这项工作?
【问题讨论】:
fgrep -x -f file2 -v file1
-x 匹配整行
-f FILE 从 FILE 中获取模式
-v 反转结果(显示不匹配)
【讨论】:
grep -F。我建议它应该是 fgrep 而不是 grep,实际上它已经被改变了。
awk 'FNR==NR{a[$0];next} (!($0 in a))' file2 file1
【讨论】:
awk 'FNR==NR{a[$0];next}!($0 in a)' file2 file1观察!
awk 'FNR==NR{ a[$0]; next } !($0 in a) || /^$/'。
在 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};
}
【讨论】:
except这样的脚本,这样你就可以说类似except file2 file1 > result这样的内容。
comm <(sort a) <(sort b) -3 → 文件 b 中不在文件 a 中的行
【讨论】: