How to Use wc Command in Bash: Count Lines, Words, and Characters
In bash, use the
wc command to count lines, words, and characters in files or input. For example, wc filename.txt shows counts for lines, words, and bytes. You can also use options like -l for lines, -w for words, and -c for bytes.Syntax
The basic syntax of the wc command is:
wc [options] [file...]
Where:
optionsspecify what to count (lines, words, bytes, characters)fileis the name of the file(s) to count. If no file is given,wcreads from standard input.
Common options include:
-l: count lines-w: count words-c: count bytes-m: count characters (useful for multibyte characters)
bash
wc [options] [file...]
Example
This example shows how to count lines, words, and bytes in a file named example.txt. It also shows how to count only lines.
bash
echo -e "Hello world\nThis is a test file." > example.txt
wc example.txt
wc -l example.txtOutput
2 6 28 example.txt
2 example.txt
Common Pitfalls
Some common mistakes when using wc include:
- Forgetting to specify a file or input, which causes
wcto wait for input from the keyboard. - Confusing
-c(bytes) with-m(characters), especially with multibyte characters like emojis. - Assuming
wccounts words the same way as a text editor; it counts groups of characters separated by whitespace.
bash
echo "emoji 😊" | wc -c # Counts bytes echo "emoji 😊" | wc -m # Counts characters
Output
9
7
Quick Reference
| Option | Description |
|---|---|
| -l | Count lines |
| -w | Count words |
| -c | Count bytes |
| -m | Count characters |
Key Takeaways
Use
wc to count lines, words, bytes, or characters in files or input.Add options like
-l, -w, -c, or -m to specify what to count.If no file is given,
wc reads from standard input until you press Ctrl+D.Use
-m to count characters correctly when dealing with multibyte characters.Remember
wc counts words as groups separated by whitespace, not necessarily what you visually expect.