Programming

[sed] Insert a line in the middle of an existing configuration file

Playing with Testing a new piece of software using a Vagrant box, I created a vagrant-install.sh in which I had to insert the line sql-mode=NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION inside an existing MySQL config file. I had to put it inside a specific section, so I targeted a line starting with datadir.

The following sed command will add the new line above it. It will update the config file by using a temporary intermediate file.

sed -n 'H;${x;s/^\n//;s/datadir.*$/sql-mode=NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\n&/;p;}' /your/file.cnf > tmp && mv tmp /your/file.cnf

How do I add a line of text to the middle of a file using bash?

Redirect output from sed 's/c/d/' myFile to myFile

Back