Linux provides a lot of tools for text-related operations. wc
is one of them. This tool is a little tool less than 10 options. In this tutorial, we will look at how to count bytes? How to count words? How to count Lines? and How to use wc with other Linux commands like find and grep?
Syntax
Syntax of wc is like below.
wc [OPTION]... [FILE]... wc [OPTION]... --files0-from=F
Help
Fast help about the wc can get with the following command.
$ wc --help

Count All Bytes, Words and Lines
As we stated before wc is a little tool. If we want to get all results wc can provide we should use it without any option like below. In the example, we provide a file named case_sensitive.c
which seems to be a C
source file and get the number of lines which is 9, number of words which is 11 and number of bytes or chars which is 78
$ wc case_sensitive.c

Count Chars
If we only want to get the number of chars we can use m
options like below.
$ wc -m case_sensitive.c

Count Words
If we only want to count words the -w
option can be used.
$ wc -w case_sensitive.c

Count Lines
If we only want to count lines -l
option can be used.
$ wc -l case_sensitive.c

Redirect To wc File
wc is generally used with other tools or external input. External input is a very useful feature of the wc. By using bash capabilities external text can be redirected to the wc as input like below. In this example we simply print file case_sensitive.c
to the standard output and this standard output is redirected with pipe operator to the wc as standard input which is processes like a file by wc.
$ cat case_sensitive.c | wc

Redirect To wc Multiple Files
Redirect is a simple mechanism. Redirecting multiple files is the same as a single file we just print files according to their names or extensions. In the example, we will redirect all files with.c
extension to the wc command.
$ cat *.c | wc

Count Files And Directories
wc can be used to count files and directories by using ls
command output. In the example, we use ls command to list all files and directories line by line and redirect to the wc.
$ ls -lh | wc -l

Usage With Grep
Another useful usage wc is using it with grep. By using grep the content of the resource files is filtered and then counted with wc. In this example, we want to count the lines where those provide int
string. We use a regular expression to filter. We only provide .c
extension files.
$ grep "^int" *.c | wc -l

Usage With Find
Another useful usage is using with find
command. find search according to specified parameters. wc can be used on the search results to count lines or others. In the example, we will search for files with .c
extension and run wc command against them to find their line counts one by one.
$ find . -iname "*.c" -exec wc -l {} \;

1 thought on “Linux wc Command Word and Line Count Tutorial With Examples”