theuniverseisflat
theuniverseisflat

Reputation: 881

Compare two files and print the differences in specific format not using "diff" command

hi I have two files each containing 1 row of data each .. Usually I just use diff command to see what is the difference between the two files.

 file1:
    a.tag
    b.tag
    c.tag

 file2:
   a.tag
   b.tag
   d.tag

I want a command that just shows me what is difference is the file and also gives me the file names in this format. I use diff but if just does not do what I want .. I want the out put to look like this ..

what I like to do: compare the two files and print only what is different in each file in this format:

 file1:c.tag
 file2:d.tag

Can you please help?

Upvotes: 3

Views: 469

Answers (1)

hek2mgl
hek2mgl

Reputation: 157992

Actually the diff command provides quite flexible output options. You can use this command:

diff 
  --unchanged-line-format='' \
  --old-line-format='file1:%L' \
  --new-line-format='file2:%L' \
  file1 file2

Output:

file1:c.tag
file2:d.tag

I'm using the %L escape sequence for both old and new lines. %L means print the contents of the line. Unchanged lines will get skipped since I pass an empty string for that.


To generalize that and make it work with arbitrary file names, you can wrap it into a shell function. Put this into your bashrc for example:

function mydiff() {
    diff 
      --unchanged-line-format='' \
      --old-line-format="$1:%L" \
      --new-line-format="$2:%L" \
      "$1" "$2"
}

Source the bashrc or start a new shell and call it like this:

mydiff file1 file2

Upvotes: 3

Related Questions