0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use wc Command in Linux: Syntax and Examples

The wc command in Linux counts lines, words, and characters in files or input. Use wc [options] [file] to get counts, where options like -l, -w, and -c specify lines, words, and bytes respectively.
📐

Syntax

The basic syntax of the wc command is:

  • wc [options] [file]

Here:

  • options specify what to count: lines, words, or bytes.
  • file is the name of the file to analyze. If no file is given, wc reads from standard input.

Common options include:

  • -l: count lines
  • -w: count words
  • -c: count bytes (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 words from typed input.

bash
echo -e "Hello world\nThis is a test file." > example.txt
wc -l example.txt
wc -w example.txt
wc -c example.txt

# Counting words from input
echo "Hello from input" | wc -w
Output
2 example.txt 5 example.txt 29 example.txt 3
⚠️

Common Pitfalls

Some common mistakes when using wc include:

  • Forgetting to specify a file or input, which makes wc wait for input indefinitely.
  • Confusing -c (bytes) with characters, which can differ with multibyte characters.
  • Using multiple options without understanding the output format.

Always check if you want lines, words, or bytes and use the correct option.

bash
wc example.txt
# Outputs lines, words, and bytes all together

wc -l -w example.txt
# This is valid but outputs lines and words in one line

# Wrong: expecting characters but using -c with multibyte text
# Use tools like 'iconv' or 'wc -m' for character count instead
📊

Quick Reference

OptionDescription
-lCount lines
-wCount words
-cCount bytes
-mCount characters (multibyte safe)
No optionCount lines, words, and bytes

Key Takeaways

Use wc -l, -w, or -c to count lines, words, or bytes respectively.
If no file is given, wc reads from standard input until you finish typing.
Use wc -m to count characters correctly with multibyte text.
Multiple options can be combined to get several counts at once.
Always check your input source to avoid wc waiting indefinitely.