3

I have a simple config file that looks a bit like this:

[sectionA]
url = value1
username = value2
password = value3

[sectionC]
url = value1
username = value2
password = value3

[sectionB]
url = value1
username = value2
password = value3

And I want to replace the username for SectionB to be valueX without touching SectionA's or SectionC's username.

I've tried some variations on sed, but as far as I've managed to fathom it seems to operate on individual lines.

How do I do the equivalent of

  1. Search for StringA (in this case [SectionB])
  2. Find the next occurrence of StringB (username = value2)
  3. Replace with StringC ('username = valueX`)
Cylindric
  • 5,858
  • 5
  • 46
  • 68
  • 1
    This is possible using the shell, but would be much easier using a language with an ini parsing library. – jordanm Aug 15 '12 at 23:06

2 Answers2

4

sed:

sed '/sectionB/,/\[/s/username.*/username = valueX/' input

awk:

awk -vRS='' -vFS='\n' -vOFS='\n' '
$1~/sectionB/{
    sub(/=.*$/, "= valueX", $3)
}
{
    printf "%s\n\n", $0
}' input
kev
  • 155,172
  • 47
  • 273
  • 272
0

This multi-line sed should do the trick:

sed -E -n '1h;1!H;${;g;s/\[sectionB\]([^[]*)username = [a-zA-Z0-9_]+/\[sectionB\]\1username = valueX/g;p;}' input.txt
mVChr
  • 49,587
  • 11
  • 107
  • 104