0

I have a situation where I would like to complete a config file in an adhoc way. I would like to do this by executing a bash script.

The initial file would be called conf.ini and looks like:

[dev]
parameter_dev = <value_dev>
[test]
parameter_test = <value_test>

I would like to execute a script that would be able to replace <value_dev> and <value_test> into their real values given on command line.

What would be the easiest way to solve this?

3
  • Please add to your question (no comment): What have you searched for, and what did you find? What have you tried, and how did it fail? Commented Apr 30, 2022 at 19:26
  • Add examples of <value_dev> and <value_test> to your question. Commented Apr 30, 2022 at 19:39
  • sed -i -e '/^parameter_dev/s/<value_dev>/real_dev_value/' -e '/^parameter_test/s/<value_test>/real_test_value/' path/to/conf.ini If you want to pass variable for, e.g. real_dev_value, then double-quote the sed expressions and use the variable name, e.g. sed -i -e "/^parameter_dev/s/<value_dev>/$real_dev_value/" ... Commented Apr 30, 2022 at 21:30

1 Answer 1

1

To update config.ini, the stream-editor sed can be used to edit config.ini in place and replace both <value_dev> and <value_test> with any values you like. To do so you will use the normal substitute form s/find/replace/ and you will include a pattern match before the substituted to only perform the substitution if the start of the line matches the pattern. For example for <value_dev> you can use an expression such as:

sed -i -e '/^parameter_dev/s/<value_dev>/real_dev_value/' conf.ini

The with only match a line beginning with "parameter_dev" and then will find <value_dev> in the line and replace it with real_dev_value. If you are calling it from within a script and want to replace with the value contained in the variable $real_dev_value, then you must use double-quotes instead of single-quotes so that variable-expansion takes place.

You can handle both replacements in a single call by simply adding another expression, e.g.

sed -i -e '/^parameter_dev/s/<value_dev>/real_dev_value/' -e \
          '/^parameter_test/s/<value_test>/real_test_value/' conf.ini

The option -i tells sed to edit the file in-place. Each -e option introduces a new expression to be applied to the file.

If using a variable for the replaced value, the double-quoted form allowing variable expansion would be:

sed -i -e "/^parameter_dev/s/<value_dev>/$real_dev_value/" -e \
          "/^parameter_test/s/<value_test>/$real_test_value/" conf.ini

Either form, using fixed strings or variables for replacement can be used on the command line or called from within a script.

Let me know if you have any questions.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.