Counting all words in multiple files and outputting each count along with its filename

StackOverflow https://stackoverflow.com/questions/18579034

  •  27-06-2022
  •  | 
  •  

Question

I am struggling with the following issue. I have a Unix directory containing ~ 60K files and I would like to be able to count all the words in each file and output a list with each count along with its corresponding filename.

Was it helpful?

Solution

This is a job for find and wc:

find . -maxdepth 1 -type f -exec wc -w {} \;

This will find all files (-type f) in the current working directory (.), without recursing into subdirectories (-maxdepth 1) and for each result will execute (-exec [...] \;) wc -w passing that filename ({}) as an argument.

wc prints the number of newlines, words, and bytes in files by default, -w specifies it should just print the word-count.

OTHER TIPS

Few more handy commands to get result from current folder

To get word in all files with file type java

find . -name '*.java' | xargs grep 'word'

To get word in all files

find . -type f | xargs grep 'word'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top