Linux wc Command


The wc (word count) command in Linux is used to count lines, words, and characters in a text file or input. It can be very helpful for quickly summarizing the content of files.

Basic Syntax

wc [options] [file...]

Common Options

  • -l : Counts only the number of lines.
  • -w : Counts only the number of words.
  • -c : Counts only the number of bytes (characters).
  • -m : Counts only the number of characters (useful for multibyte characters).
  • -L : Displays the length of the longest line in the input.

Examples with Output

Example 1: Counting Lines, Words, and Characters

Suppose you have a file named file.txt with the following content:

Hello World This is a test file. It contains multiple lines and words.
Command
wc file.txt
Output
3 12 65 file.txt

Explanation:

  • 3 is the number of lines in the file.
  • 12 is the number of words.
  • 65 is the number of characters (including spaces and newline characters).

Example 2: Counting Only Lines

To count only the lines in the file, use the -l option.

Command
wc -l file.txt
Output
3 file.txt

Explanation:

  • The output indicates that there are 3 lines in file.txt.

Example 3: Counting Only Words

To count only the words, use the -w option.

Command
wc -w file.txt
Output
12 file.txt

Explanation:

  • This shows that there are 12 words in file.txt.

Example 4: Counting Only Characters

To count the characters (bytes), use the -c option.

Command
wc -c file.txt
Output
65 file.txt

Explanation:

  • This indicates that there are 65 characters in file.txt.

Example 5: Counting Only the Longest Line

To find the length of the longest line, use the -L option.

Command
wc -L file.txt
Output
42

Explanation:

  • The output shows that the longest line in file.txt is 42 characters long.

Example 6: Counting Multiple Files

You can also count lines, words, and characters in multiple files at once. Suppose you have another file, file2.txt:

This is the second file. It has a different number of words.
Command
wc file.txt file2.txt
Output
3 12 65 file.txt 2 10 60 file2.txt 5 22 125 total

Explanation:

  • The output shows counts for each file followed by a total count for all files combined.

Summary of Common wc Commands

CommandDescription
wc file.txtCounts lines, words, and characters in file.txt.
wc -l file.txtCounts only the number of lines in file.txt.
wc -w file.txtCounts only the number of words in file.txt.
wc -c file.txtCounts only the number of characters in file.txt.
wc -L file.txtDisplays the length of the longest line in file.txt.
wc file1.txt file2.txtCounts lines, words, and characters in multiple files.

The wc command is a simple yet powerful tool for summarizing text files and understanding their content in Linux.