May 4, 2009 Leave a comment
The wc (word count) command is a very simple utility found in all Unix variants. Its purpose is counting the number of lines, words and characters of text files. If multiple files are specified, wc produces a count for each file, plus totals for all files.
When used without options wc prints the number of lines, words and characters, in that order. A word is a sequence of one or more characters delimited by whitespace. If we want fewer than the three counts, we use options to select what is to be printed: -l to print lines, -w to print words and -c to print characters. The GNU version of wc found in Linux systems also supports the long options format: –chars (or –bytes), –words, –lines.
wc [-c | -m | -C ] [-l] [-w] [ file … ]
-c Count bytes.
-m Count characters.
-C Same as -m.
-l Count lines.
-w Count words delimited by white space characters or new line characters. Delimiting characters are Extended Unix Code (EUC) characters from any code set defined by iswspace()
file Name of file to word count.
If we want to count how many words are in line 70 of file foo.txt then we use:
head -70 foo.txt | tail -1 | wc -w
Here, the command head -70 outputs the first 70 lines of the file, the command tail -1 (i.e., the number 1) outputs the last line of its input, which happens to be line 70 of foo.txt, and wc counts how many words are in that line.