I have a structure where one folder contains many subfolders that each have some .txt documents in it. I'm looking for a way to find the average text lengths (in words). Therefore I want to count the words in each .txt file using wc.

I've tried so far: ls */*.txt | wc -w (which sadly outputs only a single number).

My other attempt was using for docs in /home/.../myfolder/*.txt do wc -w docs;

Which just cancels itself after some time.


You could make use of find command to execute wc recursively:

find -type f -name "*.txt" -exec wc -w {} \;

Alternatively, via recursive glob in bash:

shopt -s globstar
wc -w **/*.txt
  • Thanks! This works excellent, is there a way to store this output in its own textfile? (Possibilty without printing the file name? Just a convenience not a requirement whatsoever). The second suggestion is much faster for btw. – Mangobae Jun 21 '18 at 20:46
  • @Mangobae Yeah, it's possible. Probably easiest would be wc -w **/*.txt | cut -f 2 > word_counts. Also beware that if you do wc -w **/*.txt | cut -f 2 > word_counts.txt , the word_counts.txt will be included in the glob, since redirections are performed first, then globs, IIRC. There's other ways,too, but that's simplest probably. – Sergiy Kolodyazhnyy Jun 21 '18 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.