How to use sed to comment and add lines in a config-file

Viewed 929

I am looking for a way to achieve the following:

A certain directory contains 4 (config) files:

  • File1
  • File2
  • File3
  • File4

I want my bash script to read in each of the files, one by one. In each file, look for a certain line starting with "params: ". I want to comment out this line and then in the next line put "params: changed according to my will".

I know there are a lot of handy tools such as sed to aid with these kind of tasks. So I gave it a try:

sed -ri 's/params:/^\\\\*' File1.conf
sed -ri '/params:/params: changed according to my will' File1.conf

Questions: Does the first line really substitute the regex params: with \\ following a copy of the entire line in which params: was found? I am not sure I can use the * here.

Well, and how would I achieve that these commands are executed for all of the 4 files?

3 Answers

So this command will comment every line beggining by params: in you files, and append a text in the next line

sed -E -i 's/^(params:.*)$/\/\/\1\nYOUR NEW LINE HERE/g'

the pattern ^(params:.*)$ will match any whole line beggining by params:, and the parenthesis indicate that this is a capturing group.

Then, it is used in the second part of the sed command via \1, which is the reference of the first capturing group found. So you can see the second part comments the first line, add a line break and finally your text.

You can execute this for all your files simply by going sed -E -i 's/^(params:.*)$/\/\/\1\nYOUR NEW LINE HERE/g' file1 file2 file3 file4

Hope this helps!

You can do this:

for i in **conf
do
    cp $i $i.bak
    sed -i 's/\(params:\)\(.*\)$/#\1\2\n\1new value/' 
done

With: \(params:\)\(.*\)

  • match params: and store it in `\1
  • match text following .*\: and store it in \2

Then create two lines:

  • The initial line commented: #\1\2\n
  • The new line with your wanted value: \1new value

This might work for you (GNU sed and parallel):

parallel --dry-run -q sed -i 's/^params:/#&/;T;aparams: bla bla' {} ::: file[1-4]

Run this in the desired directory and if the commands are correct remove the --dry-run option and run for real.

Related