Microsoft Linux TM
Microsoft Linux TM

Reputation: 412

How edit configuration files with sed

I have some configuration files(and scripts) which I want to edit with a bash script:

.
.
.
# ... foo ...
foo
.
.
.

I used this:

sed -i 's/foo/bar/'   

but as expected it will edit foo in comment line too, how can I prevent that?

Upvotes: 0

Views: 106

Answers (3)

Kalanidhi
Kalanidhi

Reputation: 5092

You can use this also

 sed '/^[^#]/s/foo/bar/g' file_name 

Upvotes: 2

arco444
arco444

Reputation: 22821

Another solution:

sed -i 's/\[^#\]foo/bar/g' filename

Upvotes: 1

anishsane
anishsane

Reputation: 20970

This should do it:

sed -i '/^ *#/! s/foo/bar/' filename

explanation (in addition to your original sed command):

  1. s command can take addresses.
  2. /^ *#/ Implies any line starting with *#
  3. ! after the address negates its effect.

So all lines NOT starting with *# are affected.

Upvotes: 4

Related Questions