Abdul Rahman
Abdul Rahman

Reputation: 1384

Reading a properties file in linux

I want to be able to read a properties file in linux, check for if certain properties exist. If the properties I am looking for exist but they dont match the value I am looking for I want to override those respective properties. If they dont exist then I want to write them to the file.

Can any linux guru help me out with this.

Thanks in advance!

Also the key names can be in the form pre1.pre2.pre3 so something like pre1.pre2.pre3 = value

The following is the properties file

net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.all.disable_ipv6 = 1
kernel.sysrq = 0
net.ipv4.ip_forward = 0
net.ipv4.tcp_syncookies = 1
net.ipv6.conf.all.forwarding = 0
net.ipv4.tcp_keepalive_time = 30
net.ipv4.tcp_keepalive_intvl = 5
net.ipv4.tcp_keepalive_probes = 5

I want to change all the settings for tcp basically.

Upvotes: 3

Views: 6831

Answers (3)

nwk
nwk

Reputation: 4050

#!/bin/sh
ensure_value() {
    file="$1"
    property="$2"
    value="$3"
    if ! grep -q "$property" "$file"; then
        echo $property = $value >> "$file"
    else
        sed -i -e "s/^$property.*/$property = $value/g" "$file"
    fi
}

# cp props props.$(date +%s).bak
ensure_value props net.ipv6.conf.all.disable_ipv6 1
ensure_value props net.ipv4.ip_forward 1
# etc.

This script is not safe or production-ready! Note that the function ensure_value evaluates regexs in property names and it can go horribly wrong if your property ends up being something like .*. Really, you should use Ansible's INI file module or similar instead.

Upvotes: 1

Jan Groth
Jan Groth

Reputation: 14656

Here are some steps that you might find useful for your script:

  • does foo.bar exist in a.properties?

if grep foo.bar a.properties ; then echo found ; else echo not found; fi

-> if tests the outcome of grep

  • replace the property with it's new value

cat a.properties | sed '/foo.bar/c\foo.bar = the new value'

-> sed with the c command changes a whole line

Looks like the last command is all you need :)

ps: I love these 'avoid bash' discussions :)

Upvotes: 3

nick
nick

Reputation: 2514

Firstly, I'd like to point out that modifying properties files via scripts can be quite dangerous so please be careful when you are testing this. I can think of two options that would get you what you want.

  1. If you want just a defaults file which won't change and simply want to replace what you have with a defaulted file, then you can keep a default version of the file on hand and do a simple diff between the properties file and your default version. If the files differ, copy the default to the actual file.

  2. Since I suspect that option 1 is not viable for you, I would look into doing sed replacements in the file. There are plenty of tutorials on how to edit files with sed out there on the internet.

Hope this helps.

Upvotes: 0

Related Questions