【问题标题】:Print lines from one file that are not contained in another file打印一个文件中不包含在另一个文件中的行
【发布时间】:2011-08-14 08:11:03
【问题描述】:

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

 contents of file1:
 string2
 string1
 string3

 contents of file2:
 string3
 string1

 Output:
 string2

是否有一个简单的脚本可以让我完成这项工作?

【问题讨论】:

标签: perl bash


【解决方案1】:
fgrep -x -f file2 -v file1

-x 匹配整行

-f FILE 从 FILE 中获取模式

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

【讨论】:

  • @ysth :是的,fgrep 表示(文件)grep,因此是 -f 选项。这可以追溯到旧版本的 unix。我认为 gnu grep 使这种区别变得多余。 ;-) 顺便提一下,FILE 可以包含多行要匹配的模式。
  • @shellter:不,我认为 fgrep 的意思是“固定的”grep;固定字符串而不是正则表达式,也可以调用为grep -F。我建议它应该是 fgrep 而不是 grep,实际上它已经被改变了。
  • @ysth :嗯,在我 X 年前读过的书中,他们说(文件)grep。每个固定字符串的 Fixed(grep) 也很好地描述了功能。感谢分享。诚挚的!
  • @j.lee 如果这个答案让你满意,请考虑采纳。
【解决方案2】:
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) || /^$/'
【解决方案3】:

在 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 &gt; result这样的内容。
【解决方案4】:

comm &lt;(sort a) &lt;(sort b) -3 → 文件 b 中不在文件 a 中的行

【讨论】:

    猜你喜欢
    • 2014-09-10
    • 1970-01-01
    • 2011-07-17
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多