Text Processing – Replace Text Within Curly Brackets Using Sed

sedtcshtext processing

I have sample file as follow :

 WEA {
     Direction = Input
     Tag = WriteEnable
     PortId = "A"
 }
 MEA {
     Direction = Input
     Tag = MemoryEnable
     PortId = "A"
 }
 CLKA {
     Direction = Input
     Tag = Clock
     PortId = "A"
 }
 TEST1A {
     Direction = Input
     Tag = None
     TieLevel = TestBench
     PortId = "A"
     SafeValue = "1'b0"
 }

I am trying to replace PortId = "A" as PortId = "A B" but in only the CLKA{ } module.

I tried to run certain modification on code given as

sed ':again;$\!N;$\!b again; s/{[^}]*}//g' file

on previous post remove text within curly brackets

I tried this sed ':again;$\!N;$\!b again; s/CLKA {[^}]*}//g' but deleted whole CLKA { } module

Best Answer

Try this:

sed '/CLKA/,/TEST1A/ { s/PortId = \"A/& B/; }' file

This sed command appends the B character to the end of pattern PortId = "A which is between two words CLKA and TEST1A.

Also you can use start(^) and end($) of line notifies to match/replace only PortId = "A" inside the CLKA { ... } module. ^ CLKA {$ matches the line which only contains CLKA { and ^ }$ matches the line if only contains }

Input:

CLKA {
     PortId = "A"
}

 CLKA {    
     Direction = Input
     Tag = Clock
     PortId = "A"
 }

Command:

sed '/^ CLKA {$/,/^ }$/ { s/PortId = \"A/& B/; }' file

Output:

CLKA {
     PortId = "A"
}

 CLKA {    
     Direction = Input
     Tag = Clock
     PortId = "A B"
 }

Note that spaces after ^ because you have a space before each lines(in your given example), if you don't have this space, remove them.