Count the number of files grepped with wc
To count the number of files grepped1 , pipe the output of grep into wc as such:
$ grep -ld s pattern file | wc -l
For example:
$ grep -ld s Alice * | wc -l
will display the number of files which include the word Alice
in the current directory.
In this example, we use the utility grep
to print the files which lines match the pattern Alice
, then we pipe the output to wc
to count the number of files.
We tell grep
to invoke the option -l
so it prints the name of the files only once. Otherwise, grep
would print each occurrence of the pattern, and possibly duplicating the name of files in the output. As a result, wc
, which counts the number of lines of the output, would count a file multiple times.
The option -d
invokes with s
tells grep
to skip directories.
To learn about wc
run $ man wc
.
To learn about grep
run $ man grep
.
grep
is copyleft-licensed and is maintained by Jim Meyering2.
wc
was first released in 19713. It is now part of the GNU coreutils package which is copyleft-licensed and is maintained by Jim Meyering4
personal computing command-line interface (cli) gnu linux trisquel shell literacy wc grep wiki office applications offline