How to merge ini file with overrides file

Viewed 413

Im looking for a way, ideally in bash to merge two ini files. Here are the details. I have one file which holds the "defaults" and another which JUST specifies the lines that should be changed.

so for example, we have the file default.ini that holds the default values:

[foo]
bar=1
baz=2

Then we have a seperate file overrides.ini, which holds the "overrides":

bar=10

What I want to end up with is:

[foo]
bar=10
baz=2

patch immediately sprang to mind, but I can't get that to work unless overrides.ini has ALL values in default.ini with bar changed (in which case I might as well just use overrides.ini)

join Seemed an option until I saw the requirement that the input files need to be sorted, which is not a possibility in my situation.

1 Answers

If that's the only bar in default.ini, you could use awk:

$ awk -F= 'NR==FNR{a[$1]=$0;next}($1 in a){$0=a[$1]}1' overrides default

Output:

[foo]
bar=10
baz=2

Explained:

$ awk -F= '              # = is the delimiter
NR==FNR {                # process overrides file
    a[$1]=$0             # hash record, first field is the key
    next                 # process next override entry
}
($1 in a) {              # if ini entry is found in a hash
    $0=a[$1]             # replace with that
}1' overrides default    # output, mind the file order
Related