Help with diff command

Platform :Oracle Linux 6.4
Shell : bash

In the below sample, although the lines in a.txt and b.txt are jumbled up, there is only one difference : b.txt has an extra line NETHERLANDS

$ cat a.txt
SPAIN
NORTH KOREA
PORTUGAL
GERMANY
SYRIA
$
$
$ cat b.txt
GERMANY
NORTH KOREA
SPAIN
PORTUGAL
SYRIA
NETHERLANDS
$
$
$ diff a.txt b.txt
1c1
< SPAIN
---
> GERMANY
2a3
> SPAIN
4d4
< GERMANY
5a6
> NETHERLANDS
$

I have two requirements

  1. Ignore the difference in the order in which the lines appear. ie. In the above example, ignore the difference
    of order of lines and consider only the line NETHERLANDS (the extra line) as the sole difference.

  2. If there is a difference between a.txt and b.txt , just print the message 'a.txt and b.txt are different'
    If there is no difference between a.txt and b.txt then print 'a.txt and b.txt are same

How can I do the above ?

diff <(sort file1) <(sort file2) > /dev/null && echo files are the same || echo files are different

Thank You Subbeh.

Two questions:

  1. What is the role of less than character in red below ?

  2. What is the role of double pipe operater ?

$ diff <(sort a.txt) <(sort b.txt) || echo 'there is a difference'
1a2
> NETHERLANDS
  1. The '<' character is used to redirect the output of sort to the diff utility. This is needed if you're not specifying a file directly to diff.

  2. || is equal to OR, && is equal to AND. In this case it means that if the diff command was succesfull, echo there is no difference (AND). If the diff command was not succesfull, echo that there is a difference (OR).

Hope this clears it up for you.

Hello John K,

Here is one more approach for same.

awk 'NR==FNR{a[$1]=$1;next} !($1 in a){print "File " FILENAME " is different from the first in value: " $1}' check_check_file_a.txt check_check_file_b.txt

Output will be as follows.

File check_check_file_b.txt is different from the first in value: NETHERLANDS

Thanks,
R. Singh

Regarding your solution :

diff <(sort a.txt) <(sort b.txt) || echo 'there is a difference'

So, basically this is what is happening:

If the exit status of the first command (diff <(sort a.txt) <(sort b.txt)) is not 0 , then the second command (echo 'there is a difference') will be executed

But why should the diff command command give an exit status 1. It executed succesfully so it should be giving an exit status of 0. Right ?

$ diff <(sort a.txt) <(sort b.txt)
1a2
> NETHERLANDS
$ echo $?
1
$

Have a look at the man pages;