Mordechai
Mordechai

Reputation: 745

Comparing two files and applying the differences

on a Linux based system, I can easily compare two files, e.g.:

diff file1.txt file2.txt

...and see the difference between them.

What if I want to take all lines that are unique to file2.txt and apply them to file1.txt so that file1.txt will now contain everything it had + lines from file2.txt that it didn't have before? Is there an easy way to do it?

Upvotes: 3

Views: 102

Answers (2)

codeforester
codeforester

Reputation: 42989

If you don't mind appending the sorted diff to your file, you can use comm:

cat file1.txt <(comm -13 <(sort f1.txt) <(sort f2.txt)) > file1.txt.patched

or

comm -13 <(sort f1.txt) <(sort f2.txt) | cat file1.txt - > file1.txt.patched

This will append the unique lines from file2.txt to file1.txt.

Upvotes: 0

Ronan Boiteau
Ronan Boiteau

Reputation: 10128

Using patch

  1. You can use diff's output to create a patch file.

    diff original_file file_with_new_lines > patch_file
    
  2. You can edit patch_file to keep only the additions, since you only want the new lines.

  3. Then you can use the patch command to apply this patch file:

    patch original_file patch_file
    

Upvotes: 3

Related Questions