August 3, 2023

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

  1. To grep is a verb. It was added to the Oxford English Dictionnary in 2003; see New words list December 2003”. Oxford English Dictionary.↩︎

  2. GNU Grep official website.↩︎

  3. wc’s first man page.↩︎

  4. Coreutils - GNU core utilities’s webpage.↩︎

personal computing command-line interface (cli) gnu linux trisquel shell literacy wc grep wiki office applications

No affiliate links, no analytics, no tracking, no cookies. © 2016-2023 Content is licensed under CC BY-NC-SA 4.0 .