Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SED command to delete empty lines till the first occurrence of sentence

My input file will be

[emptyline]
[emptyline]
aaa
bbb
[emptyline]
cc
dd

Here [emptyline] indicates blanklines.

And I need an SED command to change this into

aaa
bbb
[emptyline]
cc
dd

That is, I need to delete all the blank lines at the top alone.

I need only SED command since i need to use that in bash script.

Additional info its MAC OSx

like image 530
sam Avatar asked Nov 04 '13 12:11

sam


People also ask

What sed command removes the first occurrence of a number in all lines?

grep -n combined with cut finds the line number to be deleted.

How do you delete a line in a file using sed?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

Which command will delete all the blank lines in the field old text?

The d command in sed can be used to delete the empty lines in a file.


1 Answers

You can do it with branching in sed:

sed '/^ *$/d; :a; n; ba' file

A more efficient solution would be to use a range expression, see user2719058's answer for how to do this.

It is even more efficient if you can reduce the need for sed, see gniourf_gniourf's answer for alternatives.

This can be expressed in awk elegantly like this:

awk 'NF {f=1} f' file

Output in both cases:

aaa
bbb

cc
dd

Explanation

Both alternatives work by looking for the first non-empty line.

With sed the pattern /^ *$/d will delete all empty lines in the beginning of the file. What follows is a loop that prints the rest of the file.

awk will update NF for every line, when the line is empty NF is zero. This is exploited for setting the print-flag (f).

like image 165
Thor Avatar answered Nov 14 '22 22:11

Thor