Often you may want to delete all empty lines in a file using Bash.
There are two common ways to do so:
Method 1: Delete All Blank Lines (not including lines with only spaces)
grep . my_file.txt
Method 2: Delete All Blank Lines (including lines with only spaces)
grep "\S" my_file.txt
The following examples show how to use each of these methods in practice with a text file located at the following path on our computer:
- c:/users/bobbi/cities.txt
We can use the cat command to view the contents of this file:

The text file contains the names of various U.S. cities but several of the lines in the file appear to be empty.
Example 1: Delete All Blank Lines (not including lines with only spaces)
We can use the following syntax to delete all blank lines in the file not including lines that contain only spaces:
grep . c:/users/bobbi/cities.txt
The following screenshot shows how to use this syntax in practice:

Notice that all empty lines in the file have been deleted.
Note that the third line from the bottom of the file is not deleted because it contains spaces.
Using this syntax, we specified that lines with any content (including only spaces) should be kept in the file.
Example 2: Delete All Blank Lines (including lines with only spaces)
We can use the following syntax to delete all blank lines in the file including lines that contain only spaces:
grep "\S" c:/users/bobbi/cities.txt
The following screenshot shows how to use this syntax in practice:

Notice that all empty lines in the file have been deleted, even the lines that include only spaces.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Replace Text in String
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String
