Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question
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 at 5:52
1  
Are the files sorted on the second field? –  Cristian Ciupitu Aug 20 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. –  Adionditsak Aug 20 at 7:32

2 Answers 2

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.

share|improve this answer
    
Dang. Good idea. –  mikeserv Aug 20 at 7:11
    
@h.j.k Thank you for the review, now it is even better. –  Jayesh Aug 20 at 10:14
    
@Jayesh, np. :) –  h.j.k. Aug 20 at 10:14

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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