0

I have a short file (around 60 lines) which acts like a basic database it has three whitespace separated columns. The first one is name of the product, the second one is the price and the third one is the qunatity.

product1 5 25
product2 8 30
product3 15 80
product4 2 200

Then I create a new file which contains some modifications in the same format

product1 5 45
product3 18 80
product5 5 25

After that I want to merge the two files into one and it should look something like this

product1 5 45
product2 8 30
product3 18 80
product4 2 200
product5 5 25

I tried using diff and patch but it removed the lines which were not present in the update file. How should I tackle this problem?

4
  • Roughly how many lines does your real file contain? Commented May 3, 2020 at 8:23
  • Not that much. Around 50-60
    – Paralyz3d
    Commented May 3, 2020 at 8:23
  • Do the lines in the output file need to be in any particular order? Commented May 3, 2020 at 8:23
  • No. Only the columns have to respect the product price quantity order
    – Paralyz3d
    Commented May 3, 2020 at 8:24

1 Answer 1

2

Assuming your source file is data and your updates file is updates this short code will satisfy your requirement

awk '{ h[$1] = $0 } END { for (i in h) { print h[i] } }' data updates

awk code is split into stanzas:

{ h[$1] = $0 }                         # save each line, keyed by first element, overwriting as necessary
END { for (i in h) { print h[i] } }    # when we have read everything, print each element in the array
1
  • Thank you. Works like a charm.
    – Paralyz3d
    Commented May 3, 2020 at 8:33

You must log in to answer this question.

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