DEV Community

Cover image for Counting empty lines in a file
abbazs
abbazs

Posted on

Counting empty lines in a file

Counting Empty Lines in a File Using Bash

Counting empty lines in a file can be easily done using a combination of grep and wc commands. Below is a step-by-step guide on how to do this.

Prerequisites

  • Basic understanding of bash commands
  • A file (e.g., file.txt) with some empty lines

Step-by-Step Guide

  1. Create a Sample File (if you don't have one already):

    cat > file.txt << EOL
    Line 1
    
    Line 2
    
    Line 3
    
    Line 4
    EOL
    
  2. Command to Count Empty Lines:
    The command to count empty lines is:

    grep -v "." file.txt | wc -l
    

    Let's break down this command:

- `grep -v "." file.txt`:
    - `grep` searches for patterns within files.
    - `-v` inverts the match, so it selects non-matching lines.
    - `"."` matches any character. Therefore, `grep -v "."` matches lines that do not contain any characters (i.e., empty lines).

- `|` (pipe): Passes the output of one command as input to another command.

- `wc -l`:
    - `wc` stands for "word count".
    - `-l` counts the number of lines.
Enter fullscreen mode Exit fullscreen mode
  1. Run the Command:
    Execute the command in the terminal:

    grep -v "." file.txt | wc -l
    

    The output will be the number of empty lines in the file.

Example

Given the content of file.txt:

Line 1

Line 2

Line 3

Line 4
Enter fullscreen mode Exit fullscreen mode

Running the command:

grep -v "." file.txt | wc -l
Enter fullscreen mode Exit fullscreen mode

Output:

3
Enter fullscreen mode Exit fullscreen mode

This indicates there are 3 empty lines in the file.

Alternative Methods

Using awk:

You can also use awk to achieve the same result:

awk 'NF==0' file.txt | wc -l
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • awk 'NF==0' file.txt: awk processes each line of the file. NF stands for "Number of Fields". If NF is 0, the line is empty.
  • | wc -l: Counts the number of lines output by awk.

Using sed:

Another way is using sed:

sed -n '/^$/p' file.txt | wc -l
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • sed -n '/^$/p' file.txt: sed stands for stream editor. -n suppresses automatic printing. /^$/ matches empty lines. p prints the matched lines.
  • | wc -l: Counts the number of lines output by sed.

Summary

Counting empty lines in a file can be done using several methods in bash. The grep and wc combination is a straightforward and effective way to achieve this. Alternatives like awk and sed can also be used depending on your preference and familiarity with these tools.

Top comments (1)

Collapse
 
josephj11 profile image
Joe

You missed a really simple variation:

grep -vc "."  file.txt
Enter fullscreen mode Exit fullscreen mode

This -c gets grep to count them for you while suppressing output of matched lines.

Works in GNU grep anyway.