Quite impressive way to change configuration file settings, sed -i

sed -i - this is magic command which can be used to swap setting in configuration file.

For example i have these two lines:
cp ~/.config/deluge/{core.conf,core.conf.1}
cat ~/.config/deluge/core.conf.1 | sed -re s/\"allow_remote\"\:\ false,/\"allow_remote\"\:\ true,/ > ~/.config/deluge/core.conf
The first line is creating a backup file which will be used in next command as source file.
In second line it will replace some content from source file and put the result to the original file:
I thought this was the quickest way to get result but i was wrong.

The quickest way is to use sed -i instead of those two lines:
sed -rei s/\"allow_remote\"\:\ false,/\"allow_remote\"\:\ true,/ ~/.config/deluge/core.conf
The idea in example above is to replace "allow_remote": false, with "allow_remote": true,!
sed -r just allow to define symbols in a special way:
double quotes - \"
colon - \:
space character- \

There are another must have information related to sed -i and that is ^.* and .*$.
^.* stands for pattern from begining of line + none or more characters.
.*$ stands for pattern which match none or some character till end of line.

Let's create some example file example.cfg which will contain:
# option1=true
option2=false
#option3=yes
First example will take option2 and change value false to true:
sed -i "s/^.*option2=false/option2=true/" example.cfg
Output will be:
# option1=true
option2=true
#option3=yes
Let's change the option2 to inactive:
sed -i "s/^.*option2/#option2/" example.cfg
The output will be:
# option1=true
#option2=true
#option3=yes
In last example let's change option3 to active and force the value to no:
sed -i "s/^.*option3.*$/option3=no/" example.cfg
The command above do not care what value option3 already has.
It will just change option3 to no and set it active.

Output will be:
# option1=true
#option2=true
option3=no

No comments: