【问题标题】:How to compare the lines in two files in the columns ID?如何比较列 ID 中两个文件中的行?
【发布时间】:2014-02-06 23:29:38
【问题描述】:

我有两个动态长度从 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 

【问题讨论】:

  • 输出文件是否有任何预期的排序顺序?

标签: linux bash file compare


【解决方案1】:

使用 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.

【讨论】:

  • DigitalTrauma 非常感谢您的帮助我在最后添加了写入文件:> File3 以及如何将结果文件 File3 中的所有行都保存为变量?
  • 您能否详细更新您的请求?提供一些示例来描述您的需求,然后输入您的原始问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多