This tutorial will discuss the Linux wc command. We’ll present some basic usage as well as a couple of more advanced examples.
2. Basic Usage
wc is a handy utility to count words, lines, or bytes of the provided input, either a list of files or standard input. Let’s take a look at some basic usage.
We’ll start with a sample file:
% cat colors.txt
First, let’s get the number of lines on the file:
% wc -l colors.txt
We can also do a word count:
% wc -w colors.txt
We can also count the number of characters in the file:
% wc -m colors.txt
And since we are in a text file, a count of bytes yields the same number:
% wc -c colors.txt
3. Combining wc With grep
Combining wc with other Linux commands allows us to perform some useful tasks.
In conjunction with grep, wc gives a count of occurrences in a set of files.
For example, let’s say we need to figure out how many errors of a certain type occurred over several log files.
Let’s look at our first sample log file:
% cat log_mon.txt
12:31: error - broken pipe
12:33: warn - missing input
12:35: error - broken pipe
12:37: error - service down
12:39: warn - retry failed
And now, our second:
% cat log_tues.txt
12:41: error - broken pipe
12:43: warn - missing input
12:45: error - broken pipe
12:49: warn - retry failed
If we did grep with the -c flag, we would get a breakdown by file:
% grep -c "broken pipe" log*.txt
But to get a total count, we use wc with the -l (line count) option:
% grep "broken pipe" log*.txt | wc -l
grep sends all the results to standard input, and wc performs a line count of that input.
4. Combining wc With find
For another example, let’s combine wc with some commands to count the lines of source code in a project. Let’s say we’re looking at the Baeldung Lombok project demo. We can put find, xargs, and wc together to get a count of lines of source code in the project:
% find ./src/main -name "*.java" | xargs wc -l
In this article, we’ve seen how to use the Linux wc command. We saw some basic options as well as some ways to combine wc with other Linux commands to create some neat one-liners.