Linux commands
Browse topics

Counting lines, words and bytes with wc

Version
unversioned
Review
Draft

Summary#

wc counts newlines, words and bytes by default. Choose a flag to print a particular count.

Syntax#

sh
wc file
wc -l < file
wc -w < file
wc -c < file
wc -m < file

Redirecting the file into standard input leaves the filename out of the output. Use -m for characters and -c for bytes.

Example#

sh
(
  set -eu
  export LC_ALL=C
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  cd "$dir"

  printf 'ready\nqueued' > jobs.txt
  printf 'newlines: %s\n' "$(wc -l < jobs.txt)"
  printf 'words: %s\n' "$(wc -w < jobs.txt)"
  printf 'bytes: %s\n' "$(wc -c < jobs.txt)"
  printf '\n' >> jobs.txt
  printf 'after adding a final newline: %s\n' "$(wc -l < jobs.txt)"
)

Expected output#

Text
newlines: 1
words: 2
bytes: 12
after adding a final newline: 2

Common mistakes#

wc -l counts newline characters, so a final fragment without a newline does not increase the count. A UTF-8 character can occupy more than one byte. Use a matching locale for wc -m on multibyte text.

Version applicability#

The options here are POSIX and work with GNU coreutils and BSD or macOS wc. Character and word counts depend on the locale.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0