How to Use sed to Delete All Empty Lines in File


Often you may want to use sed to delete all empty lines in a file.

You can use the following basic syntax to do so:

sed -i '/^[[:space:]]*$/d' cities.txt

This particular example deletes all lines that contain only whitespace in the file named cities.txt.

Note that we use the -i flag in sed to delete the lines in-place.

If you simply want to delete the lines and show the resulting output then you can leave out this flag.

The following example shows how to use this syntax in practice.

Example: Use sed to Delete All Empty Lines in File

Suppose we have a text file named cities.txt that contains the following lines:

Suppose that we would like to delete all lines in this file that contain only whitespace.

We can use the following syntax to do so:

sed -i '/^[[:space:]]*$/d' cities.txt

The following screenshot shows how to use this syntax in practice:

sed delete all empty lines in file

Notice that when we use the cat command again to view the contents of the file that all empty lines have been deleted from the file.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Delete All Lines Containing Specific String
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply