0

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:

[section1]
key1=a
key2=b
[section2]
key1=a
key2=b

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 ?

TSG
  • 1,674
  • 7
  • 32
  • 51

3 Answers3

1

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.

Shane Madden
  • 114,520
  • 13
  • 181
  • 251
  • My script has to run on a variety of systems - I can only assume standard tools are installed. – TSG Oct 30 '14 at 02:27
1

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

ex $conf <<-EOF
   /^\[section1\]
   /^key1=
   s/=a/=c/
   wq
EOF

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

Ian
  • 376
  • 1
  • 6
  • 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 02: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 02: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 02: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 03:07
0

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