The
wc command is used to count the number of lines, words, and characters in a file.
Observe what happens when you run the
wc command on the following file.
$ cat letter
Dear Mom,
Final exams are coming up next week.
Please send food, clothes, and
money.
Love,
Susan
$ wc letter
9 17 101 letter
The
wc command tells you that this file has 9 lines, 17 words, and 101 characters.
You can display only the number of lines by using the
l option, the number of words by using the
w option, or the number of characters by using the
c option.
Here is the
wc command using the
l option:
$ wc l letter
9 letter
wc (word count) Command
In Unix shell programming, the `wc` (word count) command is commonly used for counting the number of lines, words, and characters in a text file. The usage of this command can be understood as follows, although variations might exist depending on the specific Unix version or shell environment.
- Count Lines: To count the number of lines in a file, you would use the `-l` option with the `wc` command. For example:
wc -l filename.txt
This command would output the number of lines present in `filename.txt`.
- Count Words: If you're interested in counting the number of words, the `-w` option is used. For instance:
wc -w filename.txt
This would display the total word count of `filename.txt`.
- Count Characters: To count the number of characters, the `-c` option can be employed. For example:
wc -c filename.txt
This command returns the number of characters (including whitespace) in `filename.txt`.
- Combined Counts: It's also possible to combine these options to get a line, word, and character count in one command:
wc -lwc filename.txt
This would produce an output showing the line count, word count, and character count, respectively.
- Output Format: Typically, the output of the `wc` command is a number followed by the filename. In cases where no filename is specified, or when using a pipe, it simply returns the count.
- Counting Bytes: Additionally, if you need to count bytes rather than characters, you can use the `-m` option:
wc -m filename.txt
- Usage in Scripts: The `wc` command is often used in shell scripts for processing text data. Its simplicity and versatility make it a handy tool in many text processing tasks.
It's important to note that the behavior of `wc` might slightly differ on different Unix-like systems or under different shell environments. Therefore, consulting the man pages (`man wc`) on your specific system might provide more precise information.
Saving the line count in a variable
To save the number of lines to a variable, embed the wc command in an assignment statement. -
The next lesson demonstrates sorting the content of a text file using the sort command.
WC Command - Exercise