BASH Programming

What Does wc Do and How to Count Words – Bash

The wc (word count) command is a simple and efficient utility in the Bash shell that allows you to count the number of words, lines, and characters in a file. It is a common tool used in Unix-based systems and is supported in almost all modern operating systems, including macOS, Linux, and Windows Subsystem for Linux.

What does wc command do?

Wc is a command-line tool that may be used to display file sizes, count the characters, words, and lines in files, among other things. With the help of various options, you can customize the output and obtain the required statistics.

To use the wc command, open your terminal or command prompt and navigate to the directory where your file is located, once you are in the directory, type the following command:

wc <file-name>

This will display the number of lines, words, and characters in the file. By default, the output of the wc command shows the number of words, lines and characters in the file, in that order. For example, if we have a bash script file called “bashfile.sh” containing the following lines of code.

#!bin/bash
name="Mark"
echo "My name is ${name}"

Now let’s use the wc command to count the number of words in the script file that i created previously and here is the output:

This output shows that the file has 3 lines, 7 words, and 49 characters, the fourth column displays the filename, which in this case is “bashfile.sh”.

The wc command also supports several options that can modify its behavior, here are some common options:

  • “-l” or “–lines” – display the number of lines in the file.
  • “-w” or “–words” – display the number of words in the file.
  • “-c” or “–bytes” – display the number of bytes in the file.
  • “-m” or “–chars” – display the number of characters in the file.
  • “-L” or “–max-line-length” – display the length of the longest line in the file.

Conclusion

The wc command is a powerful and versatile utility that allows you to count the number of characters lines and words in a file. It is an essential tool for shell scripting and is supported on almost all modern operating systems. With its various options, you can customize the output and obtain the required statistics.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.