I need to modify a config file from a bash script, changing the values of particular settings. I need to make the change using common Linux tools (sed/awk/tr/etc.). The config file can have identically named keys in different stanzas like this:


and the lines in each stanza can be in different order, with blank lines/comments between, etc. I've tried sed but can't match across lines (so I can't match the stanza names). Can someone suggest how to: 1. change the value associated with section1 key1 ? 2. Print to stdout the value associated with section1 key1 ?

closed as off-topic by mdpc, Andrew Schulman, MadHatter, masegaloeh, kasperd Nov 1 '14 at 22:44

  • This question does not appear to be about server, networking, or related infrastructure administration within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • This would have been a great on Stack Overflow. They seem to enjoy sed/awk questions. – Aaron Copley Nov 4 '14 at 22:37

You could do it with ex and a here script. For your simple example:

ex $conf <<-EOF

You search for the stanza header first, then for the variable name, then change the setting on that line only.

  • interesting...3 questions. 1:what if the key does not exist. Will it modify the key in the next section if present there? 2. Is ex found on most systems. 3: Can ex be used to print the value (of the key) to stdout? – TSG Oct 30 '14 at 2:45
  • can I replace the word "key1" with a parameter like $1 in bash? I tried replacing it in your script above, but it doesn't work – TSG Oct 30 '14 at 2:56
  • 1. Yes 2. ex is the command line mode of vi so will be found on any system which has vi. 3. not that I know of. – Ian Oct 31 '14 at 2:58
  • Yes you can replace key1 with a variable. /^${1}= will work just the same as /^key1 if key1 is the value of the first positional parameter. – Ian Oct 31 '14 at 3:07

Sounds like a job for Augeas, which will break the file down into its sections and settings in an editable hierarchy. It's not exactly a standard tool in that it probably won't be installed on a given system by default, but will be available as a package for most Linuxes.

  • My script has to run on a variety of systems - I can only assume standard tools are installed. – TSG Oct 30 '14 at 2:27

You can use sed to match across multiple lines; there's an excellent post on it here: How can I use sed to replace a multi-line string?

  • I saw that before, but could not figure out how to match with an undefined number of lines between the first line (stanza), across n random lines, to match line (key). Can you post an example? – TSG Oct 30 '14 at 13:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.