Vig*_*bhu 4 text command-line files
如何比较 2 个文件中的数据以识别常见和独特的数据?我不能一行一行地做,因为我有文件 1,其中包含 100 个 id/codes/number-set,我想将文件 2 与文件 1 进行比较。
问题是文件 2 包含文件 1 中的数据子集以及文件 2 独有的数据,例如:
file 1 file 2
1 1
2 a
3 2
4 b
5 3
6 c
Run Code Online (Sandbox Code Playgroud)
如何比较两个文件以识别每个文件共有和唯一的数据?diff
似乎无法完成这项工作。
不管你的file1和file2是否排序,使用awk命令如下:
awk 'NR==FNR{a[$0];next}!($0 in a)' file2 file1
4
5
6
Run Code Online (Sandbox Code Playgroud)
awk 'NR==FNR{a[$0];next}!($0 in a)' file1 file2
a
b
c
Run Code Online (Sandbox Code Playgroud)
awk 'NR==FNR{a[$0];next} ($0 in a)' file1 file2
1
2
3
Run Code Online (Sandbox Code Playgroud)
NR==FNR - Execute next block for 1st file only
a[$0] - Create an associative array with key as '$0' (whole line) and copy that into it as its content.
next - move to next row
($0 in a) - For each line saved in `a` array:
print the common lines from 1st and 2nd file "($0 in a)' file1 file2"
or unique lines in 1st file only "!($0 in a)' file2 file1"
or unique lines in 2nd file only "!($0 in a)' file1 file2"
Run Code Online (Sandbox Code Playgroud)
这comm
是为了:
$ comm <(sort file1) <(sort file2)
1
2
3
4
5
6
a
b
c
Run Code Online (Sandbox Code Playgroud)
第一列是只出现在文件 1 中
的行 第二列是只出现在文件 2 中
的行 第三列是两个文件共有的行
comm
需要对输入文件进行排序
要排除出现的任何列,请添加具有该列编号的选项。例如,要仅查看共同的行,请使用comm -12 ...
或仅在 file2 中的行,comm -13 ...