linux - 如何比较两个文件中的行ID列?

标签 linux bash file compare

我有两个动态长度从 1 到 30 行的文件,这些数据:

[File1] 
Time | Name | Name | ID1 | ID2 
10:50 | Volume | Xxx | 55 | 65 
12:50 | Kate | Uh | 35 | 62 
15:50 | Maria | Zzz | 38 | 67 
15:50 | Alex | Web | 38 | 5 
... 

[File2] 
Time | Name | Name | ID1 | ID2 
10:50 | Les | Xxx | 31 | 75 
15:50 | Alex | Web | 38 | 5 
... 

如何比较两个文件[仅 ID1 和 ID2 列]:[File1] 和 [File2] 将文件 {File1] 的所有第一行与 {File2] 的所有行进行比较。 如果两个文件中都存在数据则保存到文件[File3]数据添加字符* 除了文件{File3]之外还命中了来自[File1]的其他数据。

结果:

[File3] 
Time | Name | Name | ID1 | ID2 
15:50 | Alex | Web | * 38 | 5 
10:50 | Volume | Xxx | 55 | 65 
12:50 | Kate | Uh | 35 | 62 
15:50 | Maria | Zzz | 38 | 67 

最佳答案

使用awk

awk  'BEGIN{t="Time | Name | Name | ID1 | ID2"}
FNR==1{next}
NR==FNR{a[$4 FS $5];next}
{ if ($4 FS $5 in a)
       {$4="*"$4;t=t RS $0}
  else{s=s==""?$0:s RS $0}
}
END{print t RS s}' FS=\| OFS=\| file2 file1

Time | Name | Name | ID1 | ID2
15:50 | Alex | Web |* 38 | 5
10:50 | Volume | Xxx | 55 | 65
12:50 | Kate | Uh | 35 | 62
15:50 | Maria | Zzz | 38 | 67

说明

BEGIN{t="Time | Name | Name | ID1 | ID2"}   # set the title
FNR==1{next}                                # ignore the title, FNR is the current record number in the current file.for each file
NR==FNR{a[$4 FS $5];next}                   # record the $4 and $5 into Associative array a
{ if ($4 FS $5 in a)                    
{$4="*"$4;t=t RS $0}                        # if found in file1, mark the $4 with start "*" and attach to var t
else{s=s==""?$0:s RS $0}                    # if not found, attach to var s
{print t RS s}                              # print the result.

关于linux - 如何比较两个文件中的行ID列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21616329/

相关文章:

java - java .properties 文件中的括号?

Python 文件 io 缓冲

python - 在 linux "screen"中运行 Python 脚本会产生 "Cannot assign requested address"

linux - 是否可以在 Linux 中捕获应用程序屏幕缓冲区?

bash - 根据文本文件将文件移回原始位置

linux - 在 Shell 脚本中传递 'If statement' 问题

linux - 如何在没有任何用户配置的情况下启动 shell?

linux - 在 Mac OS X 上编译源代码 - 缺少 ether.h

c++ - 如何使用 windows.h 在 C++ 中创建新文件

c - 如何使用 Windows API 创建文件?