1

I have two files:

File1 has the below contents:

1 2 3 4 5 6 7 8 10

File2 has the below contents:

1
2
3
4
5
6
7
8
9
10

How can I find the difference between two files and print the odd number out and also to say from which file it is.

For example, in this case 9 only appears in File2, so how can I run a command and get output along the lines of

9 is only in File2
  • The difference between the files is that one contains numbers on a single row and the other contains numbers in a column, one per row. – roaima Nov 6 '15 at 14:09
2

If you have clean formatting (space x newline), the easiest is to transform the line to the rows and just diff them, like this:

diff <( sed -e "s/ /\n/g" h.txt ) v.txt

Where h.txt is horizontal file and v.txt is vertical file

  • 3
    <( cat v.txt ) is a UUOC.  Just use v.txt as the final argument. – G-Man Nov 6 '15 at 14:34
  • @G-Man thanks. Fixed now. Sometimes I think too complicated – Jakuje Nov 7 '15 at 11:37
1

You may want to use (G)AWK:

To find differences use AWK to convert file1.txt to line by line representation first, then pipe the result into diff:

gawk 'BEGIN {FS = " "} ; {for(i=1; i<=NF; i++) print $i}' file1.txt | diff file2.txt - 
1

There's more than one way to do it; here's comm.

First printf a header to interpret comm's output -- giving the requested filenames -- then run comm on the sorted input, suppressing lines that exist in both files (-3). The two inputs to comm are process substitutions where I use don_crissti's tr suggestion to convert spaces in File1 to newlines; then pass both files through sort, which comm requires.

printf "File1\tFile2\n"; comm -3  <(tr ' ' '\n' < File1 | sort)  <(sort File2)

Sample run

Input File1:

1 2 3 4 5 6 7 8 10 11

Input File2:

1
2
3
4
5
6
7
8
9
10

Output:

$ printf "File1\tFile2\n"; comm -3 <(sed 's/ /\n/g' File1 |sort ) <(sort File2)
File1   File2
11
        9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.