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
-
Create a Sample File (if you don't have one already):
cat > file.txt << EOL Line 1 Line 2 Line 3 Line 4 EOL -
Command to Count Empty Lines:
The command to count empty lines is:
grep -v "." file.txt | wc -lLet'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.
-
Run the Command:
Execute the command in the terminal:
grep -v "." file.txt | wc -lThe 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
Running the command:
grep -v "." file.txt | wc -l
Output:
3
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
Explanation:
-
awk 'NF==0' file.txt:awkprocesses each line of the file.NFstands for "Number of Fields". IfNFis 0, the line is empty. -
| wc -l: Counts the number of lines output byawk.
Using sed:
Another way is using sed:
sed -n '/^$/p' file.txt | wc -l
Explanation:
-
sed -n '/^$/p' file.txt:sedstands for stream editor.-nsuppresses automatic printing./^$/matches empty lines.pprints the matched lines. -
| wc -l: Counts the number of lines output bysed.
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)
You missed a really simple variation:
This
-cgets grep to count them for you while suppressing output of matched lines.Works in GNU grep anyway.