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