简体   繁体   中英

diff two files and keep just new or changed lines

I would like to write a bash script or a few shell commands that solves my problem. I have two files, old.txt, new.txt. I would like to produce a file, diff.txt, that has only the lines that have changed or are new. For instance if I had:

old.txt:

Sierra
Tango
Oscar
Victor
Whiskey
Yankee

new.txt:

Sierra
Tango
Echo
Osc__ar
Victor
Uniform
Whiskey
Yan__kee

I would want a diff.txt that looks like this:

Echo
Osc__ar
Uniform
Yan__kee

For perspective, I am writing this script to help me create a differential Motorolla S2 record for loading programs over serial port to an embedded computer. I know bash fairly well, I just don't know where to get started.

$ grep -v -f old.txt new.txt
Echo
Osc__ar
Uniform
Yan__kee
$ awk 'FNR==NR{old[$0];next};!($0 in old)' old.txt new.txt
Echo
Osc__ar
Uniform
Yan__kee

Here is how to only the new lines and changed lines using diff :

$ cat file.txt file2.txt 
line 1
line 2
line 3
line 4
line 5
line 5
$ cat file2.txt 
line 1
line 2
line 3
line 4b
line 5
line 6

$  diff --changed-group-format='***%>' --unchanged-group-format='' --new-group-format='+++%>' file.txt file2.txt
***line 4b
+++line 6

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