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

StackOverflow https://stackoverflow.com/questions/11978514

  •  26-06-2021
  •  | 
  •  

Question

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`)
Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top