Bash: How to Count Number of Blank Lines in File


Often you may want to use Bash to count the number of blank lines in a specific file.

You can use the following syntax to do so:

grep -cvP '\S' city_names.txt

This particular example will return the number of blank lines in the file named city_names.txt.

Here is how this syntax works:

  • The syntax P ‘\S‘ matches any line in the file that contains a non-space.
  • The -v command selects non-matching lines
  • The -c command prints the count of matching lines

This code basically finds all lines that contain content, then matches all lines that don’t contain content, then counts the total number of those lines.

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

Example: Use Bash to Count Number of Blank Lines in File

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 blank lines in the file.

We can use the following syntax to count the total number of blank lines in the file:

grep -cvP '\S' city_names.txt

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

Bash count blank lines in file

This returns a value of 4, which tells us that there are 4 blank lines in the file.

We can manually inspect the file to verify that this is correct.

Related Tutorials

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

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