sed: delete all blank lines from a text file

Here our requirement is to remove all the blank lines from a file.

Our sample file
[root@golinuxhub ~]# cat /tmp/file
This is line one

This is line two
This is line three

This is line four

[root@golinuxhub ~]#
Use the below command to remove all the blank lines from a text file
[root@golinuxhub ~]# sed -e ‘/^$/d’ /tmp/file
This is line one
This is line two
This is line three
This is line four
[root@golinuxhub ~]#
Here the regular expressions used are
^ – means starting with
$ – means ending with
Since we did not provided any other other character between our regular expressions, this is a notation to consider it as blank line.

To perform the action in the same file use “-i”
[root@golinuxhub ~]# sed -i ‘/^$/d’ /tmp/file

[root@golinuxhub ~]# cat /tmp/file
This is line one
This is line two
This is line three
This is line four

I hope the article was useful.

Leave a Comment