4

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.

3
  • Do you need to use sed? awk 'a||$0;!$0{a=1}' Commented May 11, 2013 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. Commented May 11, 2013 at 14:15
  • @StephaneChazelas Right, not enough coffee. awk 'a||NF;!NF{a=1}' Commented May 11, 2013 at 14:37

2 Answers 2

5

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.

2
  • That's not standard sed syntax though. Commented May 11, 2013 at 14:11
  • @Stephane The link states several non-GNU sed alternatives, though. Commented May 11, 2013 at 14:13
2

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

4
  • GNU sed (at least) has the -u option which should reduce buffering. Commented May 13, 2013 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. Commented May 13, 2013 at 10:56
  • 1
    GNU sed 4.2.2 does a 1B read here in cat file | sed -u. Commented May 13, 2013 at 11:19
  • @peterph, Indeed, that's a new feature added in 4.2.2 (see commit log) Commented May 13, 2013 at 13:01

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.