Home > OS >  sed on mac: how to print a new-line for every range-match
sed on mac: how to print a new-line for every range-match

Time:03-15

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

CodePudding user response:

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.

CodePudding user response:

Pipe the output through sed again:

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