sed – How to Delete Blank Lines Starting from Line 5

sed

I have this:

sed -i '/^$/d' temp_spec.rb

which is stripping blank lines and works well. How can I make it only do this for lines 5-999 (or ideally 5 to end-of-file).

I tried:

sed -n5,999 -i '/^$/d' temp_spec.rb
sed '5,999!d/^$/d' temp_spec.rb

but neither worked (no errors).

Best Answer

If you want to delete all blank lines starting with line 5 and keep lines 1 to 4, you can use

sed -i '5,${;/^$/d;}' temp_spec.rb

The { is the grouping operator, so the first command 5,${ means "from line 5 until the end of input ($) execute the following commands until the matching }". The commands between { and } can again be prefixed by addresses, so the inner command /^$/d means "if there is nothing between beginning (^) and end ($) of the line, delete it". Sed commands can be separated by ;. (This is a badly documented feature of sed. It's supported by most sed implementations, but it's not entirely portable.) As noted by Hauke, the ; after { is optional; the one before } is required, though.

If you want to delete all blank lines starting with line 5 and also delete lines 1 to 4, it's easier:

sed -i '1,4d;/^$/d' temp_spec.rb