How To Count the Number of Non-Empty Output Lines in Linux


We primarily use the wc (word count) command to count lines, words, bytes, and characters.

wc [flags] file.txt
wc -l : number of lines
wc -w : number of words
wc -c : number of bytes
wc -m : number of characters
wc -L : length of the longest line

Count Number of Output Lines from Another Command

Suppose we want to run main.py.

python main.py

We can count the number of lines of output by redirecting the output (|) to wc.

Note that wc -l counts empty lines.

python main.py | wc -l

In order to count only non-empty lines, we can pipe together a series of commands.

python main.py | sed '/^$/d'| awk '{print NR}' | sort -nr | sed -n '1p'

You can replace python main.py with any command that outputs to terminal.

Count Total Number of Lines in File

Suppose we wanted to count the total number of lines in file.txt.

This still includes empty lines.

wc -l file.txt

Let’s count just the non-empty lines.

sed '/^$/d' file.txt | awk '{print NR}' | sort -nr | sed -n '1p'