0

I am looking for a sed command to join all comments in source file after a Startmarker: and before endMarker (excluding) into a single line. There may possibly be a blank line before the endmarker or not.

    Startmarker: comments here comments here comments here comments here comments here comments here 
    comments here comments here comments here comments here comments here comments here comments here comments here comments here comments here comments here.
    endMarker code
    code
code
code
     Startmarker: comments here comments here comments here comments here comments here comments here 
    comments here comments here comments here comments here comments here comments here comments here comments here comments here comments here comments here.
    endMarker

code 
code

I have tried the following

awk '
  /.*Startmarker/,/.*endMarker/ {

    if (/\n/)                   
      printf "%s", $0          
    else
      print
  }
' file.name

2 Answers2

0

Would you please try the following:

awk '
/Startmarker/ {
    comment = $0        # assign the variable "comment" to the line
    f = 1               # set flag to indicate now in the comment context
    next                # skip the following codes
}
/endMarker/ {
    if (/^[[:blank:]]*endMarker[[:blank:]]*$/) {
                        # the line contains the "endMarker" keyword only
        print comment
    } else {
        sub(/endMarker/, "\n")
                        # the line contains the "endMarker" keyword and others
        print comment $0
    }
    f = 0               # reset the flag
    next
}
f {
    comment = comment $0
                        # append the line to the variable "comment"
    next
}
1                       # synonym to "print"
' file

Output with the provided example:

    Startmarker: comments here comments here comments here comments here comments here comments here     comments here comments here comments here comments here comments here comments here comments here comments here comments here comments here comments here.
 code
    code
code
code
     Startmarker: comments here comments here comments here comments here comments here comments here     comments here comments here comments here comments here comments here comments here comments here comments here comments here comments here comments here.

code
code

Hope this helps.

tshiono
  • 21,248
  • 2
  • 14
  • 22
0

With awk set a flag when the Startmarker is found:

awk '/Startmarker/ {nonewline=1}
     /endMarker/ {nonewline=0} 
     { if (nonewline==1) printf("%s",$0); else print $0; }' file.name
Walter A
  • 19,067
  • 2
  • 23
  • 43