sed: Replace Multiple Empty Lines with One Empty Line


Often you may want to use sed to replace multiple empty lines with one empty line in a file.

You can use the following basic syntax to do so:

sed '/^$/N;/^\n$/D' city_names.txt

This particular example will replace all occurrences of multiple empty lines with a single empty line in the file named city_names.txt.

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

Example: Use sed to Replace Multiple Empty Lines with One Empty Line

Suppose that we have a file named city_names.txt that contains the names of various U.S. cities.

We can use the cat command to view the contents of this file:

Notice that there are several occurrences of multiple empty lines in a row in the file.

We can use the following syntax to replace each occurrence of multiple empty lines with a single empty line instead:

sed '/^$/N;/^\n$/D' city_names.txt

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

sed replace multiple empty lines with one

Notice that all occurrences of multiple empty lines have been replaced with a single empty line in the file.

Note that you can also use the > command to save these changes to a new file if you would like:

sed '/^$/N;/^\n$/D' city_names.txt > city_names_new.txt

This particular syntax would replace all occurrences of multiple empty lines with a single empty line in the file named city_names.txt and save the results to a new file named city_names_new.txt.

Related Tutorials

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

Bash: How to Count Number of Blank Lines in File
Bash: How to Count Number of Unique Lines in File
Bash: How to Count Number of Characters in String
Bash: How to Count Number of Columns in File

Leave a Reply