'sed on mac: how to print a new-line for every range-match

For range-matches, wondering how to print a new line along with the match.

For example, if the content of a file called context.txt is like

one
begin
two
three
end
four
begin
five 
six
end
seven

then, this is the output I get with the following sed command

$ sed -n -e '/begin/,/end/p' content.txt 
begin
two
three
end
begin
five 
six
end

Instead, how can I get the output like the following:-

begin
two
three
end

begin
five 
six
end



Solution 1:[1]

This might work for you:

sed -n -e '/begin/,/end/{/end/G;p;}' file

Print the range begin to end and append the hold space when end matches.

See here for one liner explanations.

Solution 2:[2]

Pipe the output through sed again:

 sed -n -e '/begin/,/end/p' content.txt | sed 's/^end$/end\n/'

Solution 3:[3]

With your shown samples, please try following awk code.

awk '
/^end$/{
  if(found){
     print val ORS $0 ORS
  }
  found=val=""
}
/^begin$/{
  val=""
  found=1
}
found{
  val=(val?val ORS:"")$0
}
'  Input_file

Explanation: Adding detailed explanation for above.

awk '                         ##Starting awk program from here.
/^end$/{                      ##checking condition if line is equal to string end.
  if(found){                  ##Checking if found is NOT NULL.
     print val ORS $0 ORS     ##Then printing val ORS current line ORS here.
  }
  found=val=""                ##Nullifying found and val here.
}
/^begin$/{                    ##Checking condition if line is equal to string begin.
  val=""                      ##Nullifying val here.
  found=1                     ##Setting found to 1 here.
}
found{                        ##Checking if found is NOT NULL.
  val=(val?val ORS:"")$0      ##Then keep adding current line to val variable here.
}
'  Input_file                 ##Mentioning Input_file name here. 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 RavinderSingh13