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
  •  | 
  •  

문제

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`)
도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top