sed command to change an empty line with 2 lines of web content

How do I change the first empty line with 2 lines of web content? I did see an inquiry on replacing multiple blank lines with a single blank line in vim sed yet do not fairly see just how to adjust that. So, as an example, if my input documents is :

% abd
% def

% jkl

% mno

I would love to have a sed command that changes simply the first empty line with these 2 lines (one having ghi and also the various other having %) :

% abd
% def
% ghi
%
% jkl

% mno
0
2019-12-02 03:09:50
Source Share
Answers: 2

Sed matches whole lines yet does not include the newline, so an empty line will certainly simply be a vacant string. You can make use of ^ to match the start of a line and also $ to match completion, so ^$ suits an empty line. Simply change that with % ghi\n% :

sed 's/^$/% ghi\n%/'

The newline that currently existed will certainly continue to be, so you'll wind up with % ghi on one line and also % on the next


Edit : If it requires to just match as soon as after that the expression is a little bit extra difficult. The most convenient means I recognize to do it in sed is :

sed '0,/^$/ s/^$/% ghi\n%/'

The substitute is covered in an address array 0,/^$/, which suggests "only use the complying with to the lines in between 0 and also the first line that matches ^$". Given that the substitute expression look for ^$ too, the only line that is in fact mosting likely to transform is the first that matches ^$ - - the first empty line

0
2019-12-03 05:03:21
Source

NB : This addresses the initial inquiry, which requested for :

How do I change a solitary empty line with 2 lines of web content?

This does not address the 'chameleon' inquiry.


sed '/^$/{i\
% ghi\
%
d
}'

When sed locates an empty line, this inserts both lines '% ghi' and also '%', after that removes the empty line.


From the remarks

This generates a syntax mistake.

Make use of an actual covering as opposed to a sea - covering ; it will certainly conserve every person pain in the future. Area the commands on 5 lines of a straightforward documents and also usage sed -f sed.script. There are possibly various other means to attain this in C covering - this functions, though :

echo '/^$/{\'  > sed.script
echo '% ghi\' >> sed.script
echo '%'      >> sed.script
echo 'd'      >> sed.script
echo '}'      >> sed.script
sed -f sed.script data.file
rm -f sed.script
0
2019-12-03 05:02:30
Source