Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display only different rows using diff (bash)

How can I display only different rows using diff in a separate file?

For example, the file number 1 contains the line:

1;john;125;3
1;tom;56;2
2;jack;10;5

A file number 2 contains the following lines:

1;john;125;3
1;tom;58;2
2;jack;10;5

How to make in the following happen?

1;tom;58;2
like image 873
frops Avatar asked Apr 30 '12 07:04

frops


3 Answers

a.txt:

1;john;125;3 1;tom;56;2 2;jack;10;5 

b.txt:

1;john;125;3 1;tom;58;2 2;jack;10;5 

Use comm:

comm -13 a.txt b.txt  1;tom;58;2 

The command line options to comm are pretty straight-forward:

-1 suppress column 1 (lines unique to FILE1)

-2 suppress column 2 (lines unique to FILE2)

-3 suppress column 3 (lines that appear in both files)

like image 91
Anders Lindahl Avatar answered Oct 07 '22 18:10

Anders Lindahl


Assuming you want to retain only the lines unique to file 2 you can do:

comm -13 file1 file2 

Note that the comm command expects the two files to be in sorted order.

like image 39
codaddict Avatar answered Oct 07 '22 16:10

codaddict


Here's a simple solution that I think is better than diff:

sort file1 file2 | uniq -u

  • sort file1 file2 concatenates the two files and sorts it
  • uniq -u prints the unique lines (that do not repeat). It requires the input to be pre-sorted.
like image 20
wisbucky Avatar answered Oct 07 '22 16:10

wisbucky