Search code examples
regexstringsedcommentsmultilinestring

regexp and sed find block of string in multiline block untill it end with space


I try to capture those blocks of strings and comment on them using regexp and sed. Each block separated with space:

some text here 
some text here 

AppServer1:
  name: ${AppServer1.name}
  ip: ${AppServer1.ip}
   
some text here 
some text here 

AppServer2:
  name: ${AppServer1.name}
  ip: ${AppServer1.ip}

some text here 
some text here 
   

I try with this regexp:

sed E '/./{H;1h;$!d} ; x ; s/[^\$AppServer1](AppServer1)/#\1/gi'

but the result is:

 #AppServer1:
      name: $#{AppServer1.name}
      ip: $#{AppServer1.ip}

What am I missing here to comment the full string to be as below?

#AppServer1:
#      name: ${AppServer1.name}
#      ip: ${AppServer1.ip}

Solution

  • Using gnu-sed, you can do this:

    sed '/^AppServer1/I{:a; /^[[:blank:]]*$/!{s/.*/#&/; n; ba;} }' file
    
    some text here
    some text here
    
    #AppServer1:
    #  name: ${AppServer1.name}
    #  ip: ${AppServer1.ip}
    
    some text here
    some text here
    
    AppServer2:
      name: ${AppServer1.name}
      ip: ${AppServer1.ip}
    
    some text here
    some text here
    

    Details:

    • /^AppServer1/I: Search for AppServer1 case insensitive
    • {: Block start
      • :a: Make label a
      • /^[[:blank:]]*$/! If a line is not a blank line
      • {s/.*/#&/; n; ba;}: Prepend each line with #, read next line and goto label a
    • }: Block end

    Using awk you can do this:

    awk '/^AppServer1/ {b=1} b && !NF {b=0} b {$0 = "#" $0} 1' file
    
    some text here
    some text here
    
    #AppServer1:
    #  name: ${AppServer1.name}
    #  ip: ${AppServer1.ip}
    
    some text here
    some text here
    
    AppServer2:
      name: ${AppServer1.name}
      ip: ${AppServer1.ip}
    
    some text here
    some text here