Bash: How to Remove Only Double Empty Lines in File


Often you may want to use Bash to remove only double empty lines from a file.

There are two common ways to do so:

Method 1: Use sed to Remove Double Empty Lines in File

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

Method 2: Use awk to Remove Double Empty Lines in File

awk -v RS='\n\n\n' 1 city_names.txt

Both of these methods will remove double empty lines from the file named city_names.txt, while leaving single empty lines untouched.

The following examples show how to use each method in practice with the following file named city_names.txt:

Example 1: Use sed to Remove Double Empty Lines in File

We can use the following syntax with sed to remove all double empty lines from the file named city_names.txt:

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

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

sed remove double empty lines from file

Notice that this removes the double empty lines that occurred after the line containing Houston, while leaving all occurrences of single empty lines untouched.

Example 2: Use awk to Remove Double Empty Lines in File

We could also use the following syntax with awk to remove all double empty lines from the file named city_names.txt:

awk -v RS='\n\n\n' 1 city_names.txt

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

awk remove double empty lines from file

We can see that this removes the double empty lines that occurred after the line containing Houston, while leaving all occurrences of single empty lines untouched.

Note that the sed and awk approaches both produce the same results. Feel free to use whichever method you prefer.

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