提取两个文件之间的差异值[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

在linux / shell环境中工作,我该如何完成以下任务:

文本文件1包含:

1
2
3
4
5

文本文件2包含:

6
7
1
2
3
4

我需要提取文件2中不在文件1中的条目。因此在此示例中为“6”和“7”,现在它们找到了它们。例如,文件1中的6,7

我已经使用了这个awk命令

awk 'FNR==NR{a[$0]++;next}!a[$0]' file1 file2

但是这个命令只能显示差异,所以,6和7,但不是它的结果。

我怎么能从命令行执行此操作?

非常感谢!

linux bash shell awk
2个回答
1
投票

使用awk你可以这样做:

awk 'FNR==NR { seen[$0]=FILENAME; next }
  {if ($1 in seen) delete seen[$1]; else print $1, FILENAME}
  END { for (i in seen) print i, seen[i] }' file{1,2}
6 file2
7 file2
5 file1

在遍历file1时,我们将每行的column1存储在数组seen中,其值为FILENAME。接下来,在迭代file2时,我们打印每个缺失的条目,并删除是否找到条目(常用条目)。最后在END块中,我们打印数组seen中的所有剩余条目。


0
投票

comm程序将告诉您文件的共同点(或者对于一个文件是唯一的)。当文件按词汇顺序排序时,comm效果最佳。

$ echo "only in file1"; comm -2 -3 <(sort file1) <(sort file2)
only in file1
5

$ echo "only in file2"; comm -1 -3 <(sort file1) <(sort file2)
only in file2
6
7

$ echo "common to file1 and file2"; comm -1 -2 <(sort file1) <(sort file2)
common to file1 and file2
1
2
3
4
© www.soinside.com 2019 - 2024. All rights reserved.