Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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




And I want



As output.

share|improve this question
Do you need to use sed? awk 'a||$0;!$0{a=1}' – Kevin May 11 '13 at 13:56
@Kevin, $0 resolve to false if the line is empty or resolves to a numerical 0 (like 00 or 0.0 or 0e12...). Use $0 != "" instead. Test for NF for non-blank lines. – Stéphane Chazelas May 11 '13 at 14:15
@StephaneChazelas Right, not enough coffee. awk 'a||NF;!NF{a=1}' – Kevin May 11 '13 at 14:37
up vote 4 down vote accepted

See the sed FAQ here:

$ sed '0,/^$/{//d}' lines



Note this only removes truly empty lines, if you want to consider lines with whitespace you would use

$ sed '0,/^[[:space:]]*$/{//d}' lines


share|improve this answer
That's not standard sed syntax though. – Stéphane Chazelas May 11 '13 at 14:11
@Stephane The link states several non-GNU sed alternatives, though. – Adrian Frühwirth May 11 '13 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).

share|improve this answer
GNU sed (at least) has the -u option which should reduce buffering. – peterph May 13 '13 at 9:44
@peterph, with -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. – Stéphane Chazelas May 13 '13 at 10:56
GNU sed 4.2.2 does a 1B read here in cat file | sed -u. – peterph May 13 '13 at 11:19
@peterph, Indeed, that's a new feature added in 4.2.2 (see commit log) – Stéphane Chazelas May 13 '13 at 13:01

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.