0

I want to compare two files and want the output with the unique contents of both files + common content from the first file.

Example :-

File A.txt

A=x
B=y
C=z

File B.txt

A=p
D=q
E=r

Output :-

A=x
B=y
C=z
D=q
E=r

Kindly help me in resolving this. I want to perform this on Linux server so any command or shell script for this.

3
  • 2
    How is A=p not unique?
    – 123
    Jul 8, 2016 at 10:49
  • Yes that's the Problem statement. The values will be different of the common Key's in both the files. So I want that from the first file. Jul 8, 2016 at 10:56
  • 2
    Please edit your question and explain that you want us to consider this as a file with two fields, where fields are defined by =. Then, explain that you want only the unique 1st fields. how in the world did you expect us to understand this from your question?
    – terdon
    Jul 8, 2016 at 11:05

1 Answer 1

3

You can use awk:

$ awk -F= '{a[$1]++; if(a[$1]==1){print}}' A.txt B.txt  
A=x
B=y
C=z
D=q
E=r

Explanation

  • a[$1]++; : saves the 1st field as a key in the array a and increments the value associated with that key by one. This means that the first time a key is seen (for example, the first A=x), the value will be 1 but the second it will be 2. This lets us count unique elements.

  • if(a[$1]==1){print} : if the first field has only been seen once, print.

Because we're processing B.txt after A.txt, the values in A.txt are the ones that are kept.

6
  • can we do this with diff ?
    – ABcDexter
    Jul 8, 2016 at 10:52
  • Thanks but I don't want the A=p in the output. if there are same content in both the file then the content from 1st file should come not from second. Jul 8, 2016 at 10:54
  • @ArpitGupta then please edit your question and add a correct example. You say you want all unique lines from both files and A=p is unique: it's only in the second file. Do you mean that you only want the unique letters before the =?
    – terdon
    Jul 8, 2016 at 11:02
  • @terdon Sorry for that. So the Problem is we have A= in both the files. But I want the value of A= from the first file it should skip the common lines from the second one and take them from the first. Jul 8, 2016 at 11:09
  • @ArpitGupta it's OK, but please edit your question to clarify. Also, see updated answer.
    – terdon
    Jul 8, 2016 at 11:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .