skip to Main Content

i have two different txt files. The first one is the source file. The second file file b is the same file, but after some edits. New lines have been added, and some lines from file A have been deleted . Our task is to get in two new separate files the lines that have been added to file a, and in a new file the lines that have been removed from file a

a.txt

    Common
    Common
    A-ONLY
    Common

b.txt

    Common
    B-ONLY
    Common
    Common

I need as output in a separate new file to show lines removed from a.txt

output:

    A-ONLY

I then need as in a separate new file output to show lines added to a.txt

output:

    B-ONLY

How can i do it with ubuntu linux commands with sed or awk? do i first need to sort the files i compare?

2

Answers


  1. Assuming the files can be sorted before comparison:

    $ comm -23 <(sort a.txt) <(sort b.txt)
    A-ONLY
    
    $ comm -13 <(sort a.txt) <(sort b.txt)
    B-ONLY
    
    Login or Signup to reply.
  2. With GNU diff:

    $ diff --unchanged-line-format= --new-line-format= a.txt b.txt
    A-ONLY
    
    $ diff --unchanged-line-format= --old-line-format= a.txt b.txt
    B-ONLY
    

    With standard diff and awk:

    $ diff -u a.txt b.txt | awk 'NR>2 && sub(/^[-]/,"")'
    A-ONLY
    
    $ diff -u a.txt b.txt | awk 'NR>2 && sub(/^[+]/,"")'
    B-ONLY
    

    It is probably possible to implement with awk alone but you would just be trying to re-invent diff.


    With standard diff and sed:

    $ diff -u a.txt b.txt | sed -n '3,$s/^-//p'
    A-ONLY
    
    $ diff -u a.txt b.txt | sed -n '3,$s/^+//p'
    B-ONLY
    

    It’s probably very difficult to implement with sed alone, if it is even possible.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search