Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

sed

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?

like image 686
Luk Avatar asked Sep 01 '25 16:09

Luk


1 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!

like image 137
Sami Avatar answered Sep 06 '25 14:09

Sami