Monday, 23 June 2014

Editing files using bash scripts and sed

Sometimes you need to edit a setting in a conf file from a bash script.
Here's a little script that installs ntp, and edits configuration files using the sed command.

First this script removes any previous ntp servers from /etc/ntp.conf
    #remove ntp server lines
    sed -i".bak" '/^server/d' /etc/ntp.conf
the -i".bak" creates a backup of the file before changing it.
the caret ^ symbol means the start of the line. So ^server means any lines starting with "server"
the d at the end means delete the line

with all these lines removed we can add the ntp server line back in. We use >> to append the new "server" line to the end of the conf file.
    #add the local ntp server
    echo "server iburst" >> /etc/ntp.conf
Another way to edit files can be like a search and replace.
    sed -i 's/^UTC$/LOCAL/' /etc/adjtime
so we search for ^UTC$
^ means the start of a line, $ means the end of a line
^UTC$ matches lines that contain UTC and nothing else
We then specify some text to replace UTC with, in this case it's LOCAL.

Here's the complete script.

No comments:

Post a Comment