Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

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

2 Answers 2

up vote 4 down vote accepted

See 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.

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
1  
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

 
discard

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.