Counting the number of lines, words, and characters in a file
Counting the number of lines, words, and characters in a text file is frequently useful. This book includes some tricky examples in other chapters where the counts are used to produce the required output. Counting LOC (Lines of Code) is a common application for developers. We may need to count a subset of files, for example, all source code files, but not object files. A combination of wc
with other commands can perform that.
The wc
utility counts lines, words, and characters. It stands for word count.
How to do it...
The wc
command supports options to count the number of lines, words, and characters:
- Count the number of lines:
$ wc -l file
- To use
stdin
as input, use this command:
$ cat file | wc -l
- Count the number of words:
$ wc -w file $ cat file | wc -w
- Count the number of characters:
$ wc -c file $ cat file | wc -c
To count the characters in a text string, use this command:
echo -n 1234 | wc -c 4
Here, -n
deletes the...