there are similar questions here but none matches my problem exactly.
How do I remove only the first blank line from a file using sed?
Let's say I have
a
b
c
And I want
a
b
c
As output.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communitySee the sed
FAQ here:
$ sed '0,/^$/{//d}' lines
a
b
c
d
Note this only removes truly empty lines, if you want to consider lines with whitespace you would use
$ sed '0,/^[[:space:]]*$/{//d}' lines
instead.
sed
alternatives, though.
May 11, 2013 at 14:13
You can use sed
to read up to the first blank line, and then use cat
to read the rest which would be the most efficient for big files:
{ sed -n '/./!q;p'; cat; } < the-file
It only works with regular files though (not with pipes because sed
reads data by blocks and can't seek back to the line after the one where q
was called if the input is not seekable). As noted by @peterph, With GNU sed
version 4.2.2 and above, you can add the -u
flag which causes GNU sed
to read its input one byte at a time (and output one line at a time) and removes the problem with pipes (though degrading performance).
-u
, GNU sed will still read data by blocks (4k according to strace
with sed
4.2.1, eglibc 2.13, Linux amd64) so it won't help here. I've clarified what I meant by buffering.
May 13, 2013 at 10:56
sed
?awk 'a||$0;!$0{a=1}'
$0
resolve to false if the line is empty or resolves to a numerical 0 (like00
or0.0
or0e12
...). Use$0 != ""
instead. Test forNF
for non-blank lines.awk 'a||NF;!NF{a=1}'