从一个文件打印未包含在另一个文件中的行

j.l*_*lee 24 bash perl

我希望打印一个文件中但不在另一个文件中的行.但是,这两个文件都没有排序,我需要在两个文件中保留原始顺序.

 contents of file1:
 string2
 string1
 string3

 contents of file2:
 string3
 string1

 Output:
 string2
Run Code Online (Sandbox Code Playgroud)

有一个简单的脚本,我可以完成这个吗?

Cha*_*net 48

fgrep -x -f file2 -v file1
Run Code Online (Sandbox Code Playgroud)

-x匹配整条线

-f FILE从FILE获取模式

-v反转结果(显示不匹配)

  • @shellter:不,我认为fgrep意味着"固定"grep; 固定字符串而不是正则表达式,也可以作为`grep -F`调用.我建议它应该是fgrep而不是grep,事实上它已经改变了. (2认同)

yst*_*sth 6

在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};
}
Run Code Online (Sandbox Code Playgroud)