In a shell script, how do I replace the first occurrence of a string, after a different string

1.1k Views Asked by At

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`)
2

There are 2 best solutions below

2
On BEST ANSWER

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
0
On

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