Search code examples
bashshellsedreplacesh

Replacing the text that follows a given word



I need help with replacing the first line in the file that follows a given word (which will not be repeated).
I have a file with content:
"text1"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}
"text11"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}
"text21"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}

I would like to replace in Bash the line containing "text 5.0", but only the first one after the "text11" line.
To finally get the result:

"text1"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}
"text11"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "REPLACED TEXT" "1"
    "text6" "0"
}
"text21"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}

Thanks for the help.


Solution

  • With GNU sed:

    sed '/^"text11"/,/^}/s/"text5" "0"/"REPLACED TEXT" "1"/' file
    

    Only in the area with a line starting (^) with "text11" and the next line starting with } replace "text5" "0" with "REPLACED TEXT" "1".

    Output:

    "text1"
    {
        "text2" "0"
        "text3" "0"
        "text4" "0"
        "text5" "0"
        "text6" "0"
    }
    "text11"
    {
        "text2" "0"
        "text3" "0"
        "text4" "0"
        "REPLACED TEXT" "1"
        "text6" "0"
    }
    "text21"
    {
        "text2" "0"
        "text3" "0"
        "text4" "0"
        "text5" "0"
        "text6" "0"
    }
    

    See: The Stack Overflow Regular Expressions FAQ