In file1, I have

1023M  BLD
123G   DEV
945K   Deployment
4899   INT

In file2, I have

1.2G   BLD
123G   DEV
345M   Deployment
499M   INT

I wanted to compare the first field of file1 with first field of file2. I just wanted to print only the mismatching fields in file3

  • 1
    Though you haven't actually shown us what file3 might look like, this is almost certainly the perfect use case for awk.
    – HalosGhost
    Aug 20, 2014 at 5:52
  • 1
    Are the files sorted on the second field? Aug 20, 2014 at 6:14
  • I have added an answer with diff and sdiff. I do not think you should merge files and do awk on them, when there is other utils build only to do what you need. Aug 20, 2014 at 7:32

3 Answers 3


With the sample files, below command will provide you with the needed result

$ paste file1 file2 | awk '$1!=$3'

Sample output will be as below

1023M  BLD  1.2G   BLD
945K   Deployment   345M   Deployment
4899   INT  499M   INT

use redirection to file to write this to file3.


If you would like to think the problem in SQL like way, then you definitely should try a tool named 'q':

$ q 'SELECT f1.*, f2.* FROM file1 f1 JOIN file2 f2 ON f1.c2 = f2.c2 WHERE f1.c1 != f2.c1';

It is more clear and easy to understand if you're familiar with SQL query.


I would use diff or sdiff, because i feel like it is a less hacked solution, and do some manipulation with the output with awk or a similar tool, if needed.

➜  ~  sdiff 1.txt 2.txt
1023M  BLD                 |  1.2G   BLD
123G   DEV                    123G   DEV
945K   Deployment          |  345M   Deployment
4899   INT                 |  499M   INT

Then you can see the values which differ after the pipe symbol.

Grep it off to those only, like in the above answer:

➜  ~  sdiff 1.txt 2.txt | grep '|'
1023M  BLD                 |  1.2G   BLD
945K   Deployment          |  345M   Deployment
4899   INT                 |  499M   INT

I personally think this is a more smooth solution. To redirect just do:

➜  ~  sdiff 1.txt 2.txt | grep '|' > 3.txt

You can also use diff and grep to get only the fields which differ from first line:

➜  ~  diff 1.txt 2.txt | grep "^>"
> 1.2G   BLD
> 345M   Deployment
> 499M   INT

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.