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
grep -n combined with cut finds the line number to be deleted.
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.
The d command in sed can be used to delete the empty lines in a file.
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
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With