Search code examples
linuxunixawksedcsh

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


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