I have a few hundred txt files in several subfolders and I would like the count the lines in each txt file. I can do this for all txt files in the current directory by using:

for f in *.txt; do wc -l "$f"; done

which outputs:

[number] [txt filename]
[number] [txt filename]
[number] [txt filename]

Which is good. However, I don't want to to do this hundreds of times, navigating to each subfolder. The directory structure is:

...and so forth

Of note, the text files contain spaces and several dots before the .txt extension. Using the wc -l up above as written didn't produce any errors, though. Using terminal on a Mac running MacOS, which behaves like BSD for the most part.

3 Answers 3

find /the/path/to/search/ -name "*.txt" -exec wc -l {} \;
  • 2
    do also note the + variation of {}, which would allow for fewer calls to wc (as wc can accept multiple filenames)
    – Jeff Schaller
    May 24, 2019 at 15:59
  • Jeff, I didn't know that about + vs {}. Thanks for the tip. one of the things Apple got right is compiling everything in 64-bit, so the CLI tools tend to be able to handle a lot. Or, at least I think that's how that stuff works!
    – SciGuy
    May 24, 2019 at 17:46

If the directory structure is constant, then wildcards can safely expand the list (assuming there aren't so many resulting files that you exceed the command line length):

wc -l main/*/*.txt


wc -l */*/*.txt

... depending on where you're starting from and what you want to include.

find /yourpath -type f -name "*.txt" -exec wc -l {} /dev/null \;
  • 3
    There's not really a need to use /dev/null here; perhaps you picked it up from some grep examples?
    – Jeff Schaller
    May 24, 2019 at 15:58

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.