【问题标题】:Bash: finding which lines have not changed between two filesBash:查找两个文件之间哪些行没有更改
【发布时间】:2015-08-06 21:14:40
【问题描述】:

我有两个文件,每个文件都包含一个计数列表,其中每一行是特定进程的计数,例如

文件 1:

10
13
12
7
15

文件 2:

13
13
15
21
15

我希望做 diff 的逆操作,即找出两个文件之间哪些行没有改变。理想情况下,输出将是行号,以识别停滞的进程,file_out:

2
5

关于潜在的重复:“反向差异”问题实际上是在寻找相同的行,无论它们在文件中的位置如何(尽管您必须对文件进行排序)。我要求直接比较每个文件中的同一行。

【问题讨论】:

  • @kenorb 你说得对,措辞相似。然而,在这个问题中,原始文件的行号很重要。这与链接的问题不同,这里的答案也相应不同。

标签: linux bash file compare


【解决方案1】:

你可以使用这个 awk 命令:

awk 'FNR==NR{a[FNR]=$0; next} a[FNR] == $0{print FNR}' file1 file2
2
5

awk 命令的分解:

NR == FNR {                  # While processing the first file
  a[FNR] = $0                # store the line by the line #
  next                       # move to next record
}
                             # while processing the second file
a[FNR] == $0                 # current record is same as array value 
                             # with index of current line #
print FNR                    # print record number

【讨论】:

    【解决方案2】:
    $ paste file1 file2 | awk '$1==$2{print NR}'
    2
    5
    

    工作原理

    第一步使用paste 将行合并在一起:

    $ paste file1 file2
    10      13
    13      13
    12      15
    7       21
    15      15
    

    第二步是 awk,它检查两列是否相等,$1==$2。如果是,则打印行(记录)编号NR

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多