0
0
Bash-scriptingHow-ToBeginner · 3 min read

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.txt
Output
5 example.txt
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to specify the filename, which causes wc to wait for input from the keyboard.
  • Using wc without -w will 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

CommandDescription
wc -w filenameCount words in the specified file
wc -l filenameCount lines in the file (not words)
wc -c filenameCount bytes in the file
wc filenameCount 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.