Suppose you have a file that looks like this:


line 1
line 2 

line 3
line 4

line 5

That's 7 lines. But what if you only care about the non-blank lines, then it's 5.
If the number of lines is so large that you can't do it easily with your eyes, you can use wc -l. For example:


$ cat file-with-blank-lines.txt | wc -l
    7

In fact, if the lines you're counting you can use wc directly:


$ wc -l file-with-blank-lines.txt
    7 file-with-blank-lines.txt

But perhaps the lines you want to count are coming from something else. For example on macOS you get the builtin pbpaste command. You select the lines above and ⌘-C to copy them to your clipboard:


$ pbpaste | wc -l
    7

Now, suppose you only want to count the non-empty lines; you can use awk:


$ cat file-with-blank-lines.txt | pbcopy
$ pbpaste | awk 'NF > 0'
line 1
line 2
line 3
line 4
line 5
$ pbpaste | awk 'NF > 0' | wc -l
    5

Cool! Or rather; by blogging about this tip I won't forget it myself.

Comments

Emi

$ grep -v "^$" myfile.txt | wc -l

Your email will never ever be published.

Previous:
gg commit with suggested --no-verify August 29, 2025 Bun
Next:
How I end-to-end test my Bun CLI app September 18, 2025 Bun
Related by category:
hylite as an executable October 15, 2025 Linux
gg2 - a new CLI for helping me manage git branches August 6, 2025 macOS
Find the source of an alias in bash September 29, 2025 Bash, Linux, macOS
Set up iTerm to delete whole words on Option-Backspace May 13, 2025 macOS