PDA

View Full Version : Replace a string in a file with bash script


scifo_dk
February 27th, 2009, 12:08 PM
Hi there.

I need at bash script to open a file and replace a single line of code, with one i provide.
To be more exact, i want it to:
gksu gedit /etc/init.d/rc

and replace CONCURRENCY=none with CONCURRENCY=shell and save.

Can anyone tell me how to do that?

Kind regard
Scifo

geirha
February 27th, 2009, 01:07 PM
sed is your friend.
sudo sed -i 's/CONCURRENCY=none/CONCURRENCY=shell/' /etc/init.d/rc

http://manpages.ubuntu.com/manpages/intrepid/en/man1/sed.1.html

monkeyking
February 27th, 2009, 04:48 PM
just take care that none, only appears once in the file.

leewebb
February 28th, 2009, 05:40 AM
sed is your friend.
sudo sed -i 's/CONCURRENCY=none/CONCURRENCY=shell/' /etc/init.d/rc

http://manpages.ubuntu.com/manpages/intrepid/en/man1/sed.1.html

This is a good example of how to do it, but I would personally enhance it further by specifying that only lines beginning with CONCURRENCY are replaced. This ensures that only config item is changed (as opposed to comments etc, unless you want them done as well), but also to avoid other tests that may hardwire CONCURRENCY=none (which /etc/init.d/rc does)

So this gives:

sudo sed -i 's/^CONCURRENCY=none/CONCURRENCY=shell/' /etc/init.d/rc

scifo_dk
March 4th, 2009, 08:08 AM
Great work guys!

Exactly what I needed.

Thank you for your help, I might need more like this in the near future. :D

// Scifo