How to consider next line content with sed search and replace command?

Issue

I am trying to replace following pattern

  }

  if {[info exists env(PATH)]} {
     tcl::native_code " Message"
     tcl::native_code " Done"

with

    tcl_block

    if {[info exists env(PATH)]} {
       puts " Message"
       puts " Done"

with the help of sed/awk(preferable sed). But not sure how to consider the content of next line content while searching the pattern.

Please help!
BR,
Learner!!

Solution

You can try this sed with conditions mentioned in your comments.

sed '/\}/ {N;N;/if {\[info exists env(PATH)\]} {/ s/\}/tcl_block/};/tcl_block/ {N;N;/tcl/ s/tcl::native_code\|ntcl::native_code/puts/g}' $inputfile

Output

tcl_block

  if {[info exists env(PATH)]} {
     puts  "Message"
     puts  "Done"

If you have more tcl::native_code lines than the example data, then a complete recode may be needed but to handle it with this current code, add more N; lines to take into account for the substitution within the second condition.

sed '/\}/ {N;N;/if {\[info exists env(PATH)\]} {/ s/\}/tcl_block/};/tcl_block/ {N;N;N;/tcl/ s/tcl::native_code\|ntcl::native_code/puts/g}' $inputfile

Answered By – HatLess

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published