Possible Duplicate:
How can I replace lines in a text file with lines from another file based on matching key fields?
I want to merge the following files and I want the contents of FileB.txt to overwrite FileA.txt where there are common lines, but I don’t want to completely replace FileA.txt with FileB.txt.
For example:
File A:
# cat FileA.txt
interface.1.type = ethernet
interface.1 = A
interface.1.ip = 192.168.1.1
interface.1.netmask = 255.255.255.0
interface.1.dhcp = false
File B:
# cat FileB.txt
interface.1 = B
interface.1.ip = 192.168.1.1
interface.1.netmask =
interface.1.dhcp = true
interface.1.dhcp.range = 192.168.1.1,192.168.1.15
interface.1.extraline =
In this case
The merge result should be:
# cat FileA.txt
interface.1.type = ethernet
interface.1 = B
interface.1.ip = 192.168.1.1
interface.1.netmask =
interface.1.dhcp = true
interface.1.dhcp.range = 192.168.1.1,192.168.1.15
interface.1.extraline =
So anything before the ‘=’ on each line should be checked and matched between FileA.txt and FileB.txt. If any after the ‘=’ on FileB.txt differs from FileA.txt then whatever is in FileB.txt should be written to FileA.txt.
Try this
sortcommand:-t=: split the lines into fields on the ‘=’, so you are sorting on the keys-k1,1: sort on the first field. This is important, as duplication (see below) dependsonly on the specified sort field.
-u: eliminate duplicates. If two lines have the same key, only the first is kept.-s: stable sort. If two lines are identical based on their sort field, the line thatis seen first in the input remains first in the output.
By putting
FileB.txtin the list of input files first, you ensure that the line fromFileB.txtis chosen over the line fromFileA.txtif they share the same key.