Skip to content

The wc Command: Counting Words, Lines, and Characters

Summary

The wc command is a versatile utility for counting words, lines, characters, and bytes in a file or from standard input. It's a quick and easy way to get a statistical overview of text data.

Introduction

The wc command, short for "word count," is a fundamental tool in the Linux command-line environment. It analyzes the content of files (or standard input) and reports the number of lines, words, characters, and bytes. It's a simple yet powerful command for quickly assessing the size and structure of text-based data.

Use case and Examples

Basic Word Count

wc myfile.txt
This command will output the number of lines, words, and characters in the file myfile.txt, followed by the filename.

Counting Lines Only

wc -l myfile.txt
This command specifically counts and displays only the number of lines in myfile.txt.

Counting Words Only

wc -w myfile.txt
This command counts and displays only the number of words in myfile.txt.

Counting Characters Only

wc -m myfile.txt
This command counts and displays only the number of characters in myfile.txt. Note the use of -m instead of -c to correctly handle multi-byte characters in UTF-8 encoded files.

Counting Bytes Only

wc -c myfile.txt
This command counts and displays only the number of bytes in myfile.txt. This is useful for determining the raw file size.

Piping Output to wc

cat myfile.txt | wc -l
This command uses cat to output the contents of myfile.txt and pipes it to wc -l, which then counts the number of lines received from standard input.

Multiple Files

wc file1.txt file2.txt file3.txt
This command will output the counts for each file individually, followed by a total count for all files combined.

Commonly used flags

Flag Description Example
-l Counts the number of lines. wc -l myfile.txt
-w Counts the number of words. wc -w myfile.txt
-m Counts the number of characters. Handles multi-byte characters correctly. wc -m myfile.txt
-c Counts the number of bytes. wc -c myfile.txt
-L Prints the length of the longest line. wc -L myfile.txt


Share on Share on

Comments