Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Replace config file entry or append if not found

Suppose you need to replace whatever current setting for a particular application to a specific setting. It doesn't matter what it was before, or if it was absent. You want to define it. Suppose you want to replace the session pam_mkhomedir setting in /etc/pam.d/common-session to be required. If it was optional, replace it. If it wasn't listed at all, add it. This line updates an answer on stackoverflow.

sed -i -e '\|session.*pam_mkhomedir.so|h; ${x;s/mkhomedir//;{g;tF};a\' -e 'session\trequired\tpam_mkhomedir.so umask=0022' -e '};:F;s/.*mkhomedir.*/session\trequired\tpam_mkhomedir.so umask=0022/g;' /etc/pam.d/common-session

The -i makes the change inline directly in the file. I write deployment scripts so I don't care about displaying the output; I want to change the original. Basically the command looks like this:

sed -e '\|variable.*(possible|values|go|hereornot)|h; ${x;s/variable//;{g;tF};a\' -e 'variable updatedvalue1 updatedvalue2' -e '};:F;s/.*variable.*/variable thisvalueadded1/g;' /etc/inputfile

Questions? I would be happy to explain this if you want a guided tour.

References

http://stackoverflow.com/a/3560072/3569534

Comments