简体   繁体   English

使用linux diff进行编译时如何添加新的空行代替已删除的空行

[英]How to add new empty line in place of deleted one when compering using linux diff

I have two files a.txt and b.txt 我有两个文件a.txt和b.txt

a.txt content a.txt内容

a
b
c

b.txt content b.txt内容

a
c
d

I need file c.txt with following content: 我需要具有以下内容的文件c.txt

a

c
d

File b.txt does not have b line but has extra d line. 文件b.txt没有b行,但具有额外的d行。 File c.txt has empty line in place of missing b and has new line d. 文件c.txt用空行代替缺少的b并用新行d代替。

How can i achive that? 我怎样才能做到这一点?

Here's using sed to modify the output of diff -u : 这是使用sed修改diff -u的输出:

$ diff -u a.txt b.txt
--- a.txt   2016-07-26 18:27:59.000000000 +0200
+++ b.txt   2016-07-26 18:28:05.000000000 +0200
@@ -1,3 +1,3 @@
 a
-b
 c
+d

We'd like to remove the three first lines of that output, then replace every line that starts with a - with a blank line. 我们想删除该输出的前三行,然后将以-开头的每一行替换为空白行。 Finally we need to remove the first character from each remaining line: 最后,我们需要从其余各行中删除第一个字符:

$ diff -u a.txt b.txt | sed  -e '1,3d' -e 's/^-.*$//' -e 's/^.//'
a

c
d

This may fail if diff finds too many similar lines in between the differing lines, in which case it will print a new @@ -line. 如果diff在不同行之间发现太多相似行,则可能会失败,在这种情况下,它将打印新的@@ -line。 We may solve this by asking for more lines of unified context with -U : 我们可以通过使用-U请求更多行统一上下文来解决此问题:

$ diff -u -U 100 a.txt b.txt | sed  -e '1,3d' -e 's/^-.*$//' -e 's/^.//'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM