How to make and apply (patch) one side diff

configurationdiff()patchscriptingtext processing

I want to make a shell script that updates a config file.

The file present on the server has information, like various IP addresses.

The new file has more code, from new configs added to the system, I want to be able to add these new configurations to the server file without changing what's already configured there

example:

server file

[config]
ip=127.0.0.1
port=22

new file

[config]
ip=XXX.XXX.XXX.XXX
port=XX
user=root

I want the resulting file to be

[config]
ip=127.0.0.1
port=22
user=root

How would be a good way to do that? I don't want to rely on line position and such, because the actual config files are quite large and more lines could have been added to the server file.

I've tried to make a diff from the files and apply the patch, but it didn't work.

Thanks for any help.

Best Answer

As Gilles says, you'll need to use a tool that knows about the format of your config files. For your particular example, you can use a short Python script that uses the built-in ConfigParser module.

  • First, let's say your original configuration file on the server is original.cfg:

    [config]
    ip=127.0.0.1
    port=22
    
  • Now put your changes in a new file called update.cfg:

    [config]
    user=root
    

    This file should have new or changed entries listed under the section heading where you would like them to go.

  • Then run a script like this one:

    #!/usr/bin/env python
    
    import ConfigParser
    
    config = ConfigParser.ConfigParser()
    
    # Read the original config file
    with open('original.cfg', 'r') as f:
        config.readfp(f)
    
    # Also read in all the changes we'd like to make
    with open('update.cfg', 'r') as f:
        config.readfp(f)
    
    # Write the full new config file out
    with open('output.cfg', 'w') as f:
        config.write(f)
    

There are, of course, plenty of variations on how to do this. For example, the config changes could be coded directly into the Python script rather than read from a separate update.cfg file. This should give you a good base to get started, though.

Related Question