How to Count Words in a File Using Bash Commands
Use the
wc -w filename command in Bash to count the number of words in a file. This command outputs the word count followed by the filename.Syntax
The basic syntax to count words in a file is:
wc: stands for word count utility.-w: option to count words only.filename: the file you want to count words in.
bash
wc -w filename
Example
This example shows how to count words in a file named example.txt. It prints the number of words followed by the filename.
bash
echo "Hello world from Bash scripting" > example.txt
wc -w example.txtOutput
5 example.txt
Common Pitfalls
Common mistakes include:
- Forgetting to specify the filename, which causes
wcto wait for input from the keyboard. - Using
wcwithout-wwill count lines, words, and bytes, which may confuse you. - Counting words in a file that does not exist will cause an error.
bash
wc example.txt # Counts lines, words, and bytes wc -w # Waits for input from keyboard until Ctrl+D wc -w missing.txt # Error: No such file or directory
Quick Reference
| Command | Description |
|---|---|
| wc -w filename | Count words in the specified file |
| wc -l filename | Count lines in the file (not words) |
| wc -c filename | Count bytes in the file |
| wc filename | Count lines, words, and bytes all together |
Key Takeaways
Use
wc -w filename to count words in a file quickly.Always specify the filename to avoid waiting for keyboard input.
wc without options shows lines, words, and bytes together.Check if the file exists before running the command to avoid errors.