2

I have two files file1 and file2. I want to print the new line added to file2 using diff.
file1

/root/a
/root/b
/root/c
/root/d

file2

/root/new
/root/new_new
/root/a
/root/b
/root/c
/root/d

Expected output

/root/new
/root/new_new

I looked into man page but there was no any info on this

Dsujan
  • 411
  • 3
  • 14
  • Duplicate of https://stackoverflow.com/questions/15384818/how-to-get-the-difference-only-additions-between-two-files-in-linux . – Jordan Samuels Mar 29 '18 at 14:08
  • @Jordan Samuels As someone already commented in that other question, it will leave you with a + at the beginning of the line. – pcjr Mar 29 '18 at 15:16

3 Answers3

2

If you don't need to preserve the order, you could use the comm command like:

comm -13 <(sort file1) <(sort file2)

comm compares 2 sorted files and will print 3 columns of output. First is the lines unique to file1, then lines unique to file2 then lines common to both. You can supress any columns, so we turn of 1 and 3 in this example with -13 so we will see only lines unique to the second file.

or you could use grep:

grep -wvFf file1 file2

Here we use -f to have grep get its patterns from file1. We then tell it to treat them as fixed strings with -F instead of as patterns, match whole words with -w, and print only lines with no matches with -v

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • As I needed to maintain the order so i used the `grep -wvFf file1 file2` but there was no output. Ain't it supposed to print the added line? – Dsujan Mar 29 '18 at 14:59
  • @SujanDulal one thing I noticed from your sample input is one of them has carriage returns and the other doesn't. If possible you might want to run `dos2unix` on both files so you get rid of those different line endings (otherwise they will be treated as part of the match) – Eric Renouf Mar 29 '18 at 15:02
  • I actually jumbled the file during input that was the problem. Thank you for the suggestion. I will filter out the carriage return. – Dsujan Mar 29 '18 at 15:10
1

Following awk may help you on same. This will tell you all those lines which are present in Input_file2 and not in Input_file1.

awk 'FNR==NR{a[$0];next} !($0 in a)'  Input_file1  Input_file2
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
1

Try using a combination of diff and sed.

The raw diff output is:

$ diff file1 file2
0a1,2
> /root/new
> /root/new_new

Add sed to strip out everything but the lines beginning with ">":

$ diff file1 file2 | sed -n -e 's/^> //p'
/root/new
/root/new_new

This preserves the order. Note that it also assumes you are only adding lines to the second file.

pcjr
  • 419
  • 2
  • 6