首页 > 解决方案 > 如何防止 GNU diff 对补丁行进行分组?

问题描述

我从别人那里继承了对一组 html 文件的两个版本的维护,一个较大的有翻译,另一个较短,没有翻译。短文件和长文件的正文仅在包含翻译的行上有所不同。但也有一些特定内容在这些文件中的某处不常见,必须保持不变。

短.html

Salve<br/>
Quomodo te habes?<br/>
Some lines specific to short.html

长.html

Salve<br/>
Hello!<br/>
Quomodo te habes?<br/>
How do you do?<br/>
Some other lines specific to long.html

我用来编辑较短的文件,并且为了不重复该工作两次,我查看与 GNU 的差异diff来创建一个补丁文件,以便对较大的文件应用相同的更正。

diff short.html.orig short.html > short.diff
patch -z .orig long.html short.diff

这很有魅力,因为patch它足够聪明,可以跳过垃圾寻找修补的位置,直到我不得不更正短文件中的相邻行

在这种情况下,diff命令的输出如下所示:

1,2c1,2
< Salve<br/>
< Quomodo te habes?<br/>
---
> Salvete<br/>
> Quomodo vos habetis?<br/>

并且该补丁被拒绝,因为我认为在 long.html 中patch找不到包含Salve...Quomodo...替换的任何两行块,因为在每行之后插入翻译的较长版本中这两行不再相邻。只要补丁被逐行应用,它就可以很好地工作,但是当补丁被分组到一个块中时(它们称为大块),它就不再起作用了。

我的问题是:如何防止diff将要修补的行分组为大块,以便逐行应用补丁?

不用多说,我希望将diff上面命令的输出更改为:

1c1
< Salve<br/>
---
> Salvete<br/>
2c2
< Quomodo te habes?<br/>
---
> Quomodo vos habetis?<br/>

标签: bashdiffpatch

解决方案


我找到了解决我的问题的方法,而不是一种解决方法,我不改变diff. 使用 AWK,可以处理其输出以将具有多行的大块切割成一行的切片:

diffungroup

awk -F ',|c' ' # process lines as "3,4c3,4" and following lines
  /[0-9]+,[0-9]+c[0-9]+,[0-9]+/ {
    ss = $1; se = $2; ds = $3; de = $4; 
    for (i = ss; i <= se; i++) {
      getline
      a[i] = $0
    }
    getline # skip "---"    
    i = ss
    for (j = ds; j <= de; j++) {
      print i "c" j
      print a[i++]
      print "---"
      getline
      print $0
    } 
    next 
  }
  { print }
' "$@"

它转换如下输出diff

1,2c1,2
< Salve<br/>
< Quomodo te habes?<br/>
---
> Salvete<br/>
> Quomodo vos habetis?<br/>

进入:

1c1
< Salve<br/>
---
> Salvete<br/>
2c2
< Quomodo te habes?<br/>
---
> Quomodo vos habetis?<br/>

在上述问题中解释的上下文中,我以以下方式调用它:

diff short.html.orig short.html > short.diff
./diffungroup short.diff > long.diff
patch -z .orig long.html long.diff

而且,正如我上面所说,它就像一个魅力。


推荐阅读