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 -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.
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
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
:awk
processes each line of the file.NF
stands for “Number of Fields”. IfNF
is 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
: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 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.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.