Home > other >  Introducing blank lines separating matched sections
Introducing blank lines separating matched sections

Time:11-05

I have this bash function that prints lines between Mode: org and # End of org. I would like for matched sections to be separated by a blank line.

capture ()
{
 local efile="$1"
 
 local charcl begorg endorg
   charcl_ere='^[[:space:]]*([#;!] |@c|\/\/)[[:space:]]*'
   charcl_bre='^[[:space:]]*\([#;!]\ \|@c\|\/\/\)[[:space:]]*'

   begorg="${charcl_bre}"'Mode: org$'
   endorg="${charcl_bre}"'# End of org$'

   mdr='^Mode: org$' ; edr='^# End of org$'
   
   sed -n "/$begorg/,/$endorg/ s/$charcl_bre//p" "$efile" |
    sed "/$mdr\|$edr/d"
}

This is the input

cat /home/flora/docs/recnotes.txt
   ## Mode: org
   #  Assigns shell positional parameters or changes the values of shell
   #  options.  The -- option assigns the positional parameters to the
   #  arguments of {set}, even when some of them start with an option
   #  prefix `-'.
   ## # End of org

     ;; Mode: org
     ;  Assigns shell positional parameters or changes the values of shell
     ;  options.  The -- option assigns the positional parameters to the
     ;  arguments of {set}, even when some of them start with an option
     ;  prefix `-'.
     ;; # End of org
 
       @c Mode: org
       @c  Assigns shell positional parameters or changes the values of shell
       @c  options.  The -- option assigns the positional parameters to the
       @c  arguments of {set}, even when some of them start with an option
       @c  prefix `-'.
       @c # End of org

CodePudding user response:

With GNU sed:

sed -n "/Mode: org/,/# End of org/{/# End of org/G;p}" recnotes.txt

G: Append "hold space" to "pattern space" (current row). "Hold space" contains a line break by default.

Disadvantage: There is a blank line at the end.

CodePudding user response:

I assumed by lines between that you didn't mean including the lines with Mode: org and # End of org. You didn't specify that. Try:

perl -nlE'$p=/Mode: org/?1:/# End of org/?0*say$":$p&&$p say' recnotes.txt

If it's important to avoid the empty separation line at the end, try:

perl -nlE'$p=/Mode: org/?1:/# End of org/?0*do{eof||say("")}:$p&&$p say' r.txt

CodePudding user response:

I have come up with a straightforward way using

   sed -n "/$begorg/,/$endorg/ s/$charcl_bre//p" "$efile" |
    sed "/$mdr/d" | sed "s/$edr//"
  • Related