How to Count the Number of Non-Empty Lines in Text File in Linux

Published November 18, 2026

How to Count the Number of Non-Empty Lines in Text File in Linux

Question

You have a text file names.txt and want to count the number of non-blank lines in that file. How do you do that on Linux or macOS?

Environment

  • Operating system: Linux, macOS, FreeBSD, NetBSD and other BSDs
  • Shell: bash, zsh, etc

Solution 1: Using grep -cv

Using grep -cv is the fastest way. This command skips lines that have nothing, and counts the other lines.

grep -cv '^$' names.txt

You can also do this, and skip whitespaces or tabs.

grep -cv '^[[:space:]]*$' names.txt

A third way is to match non-empty lines and add them to the count.

grep -c . names.txt

Solution 2: Using awk

You can count lines with content with awk. This counts lines with at least one non-whitespace field.

awk 'NF' names.txt | wc -l

You can also count without piping to wc. This command will work for calculating and printing the total directly (the +0 ensures it prints 0 if the file is empty).

awk 'NF{c++} END{print c+0}' names.txt

The above command is complicated, but works.

Solution 3: Using sed

A combination of sed with wc can be used too. This command deletes blank lines by strip out empty and whitespace-only lines before counting.

sed '/^[[:space:]]*$/d' names.txt | wc -l

Similar questions

  • How do I count non-blank lines in a text file?
  • How do I do wc -l and skip the blank lines?
  • Is there a way that I can use awk and sed to count the number of non-blank lines in a text file?

If you have questions similar to these, just follow the steps in the first

Conclusion

What worked best for you? Add a comment below. Thanks for reading.

Related Posts

If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.

Disclaimer: Our website is supported by our users. We sometimes earn affiliate links when you click through the affiliate links on our website.

Last Updated: November 18, 2026.     This post was originally written on November 17, 2026.