How do I replace the first blank line with two lines of content? I did see a question on replacing multiple blank lines with a single blank line in vim sed but don't quite see how to adapt that. So, for example, if my input file is:
% abd
% def
% jkl
% mno
I would like to have a sed command that replaces just the first blank line with these two lines (one containing ghi
and the other containing %
):
% abd
% def
% ghi
%
% jkl
% mno
Best Answer
Sed matches entire lines but doesn't include the newline, so a blank line will just be an empty string. You can use
^
to match the beginning of a line and$
to match the end, so^$
matches a blank line. Just replace that with% ghi\n%
:The newline that already existed will remain, so you'll end up with
% ghi
on one line and%
on the nextEdit: If it needs to only match once then the expression is a bit more complicated. The easiest way I know to do it in
sed
is:The replacement is wrapped in an address range
0,/^$/
, which means "only apply the following to the lines between 0 and the first line that matches^$
". Since the replacement expression checks for^$
as well, the only line that's actually going to change is the first that matches^$
-- the first blank line