简体   繁体   中英

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 content

a
b
c

b.txt content

a
c
d

I need file c.txt with following content:

a

c
d

File b.txt does not have b line but has extra d line. File c.txt has empty line in place of missing b and has new line d.

How can i achive that?

Here's using sed to modify the output of 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. We may solve this by asking for more lines of unified context with -U :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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