2

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:

-main
    -folder1
        textfile1.txt
        textfile2.txt
        textfile3.txt
    -folder2
        textfile4.txt
        textfile5.txt
        textfile6.txt
    -folder3
        textfile7.txt
        textfile8.txt
        textfile9.txt
...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
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 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 at 17:46
0

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

or

wc -l */*/*.txt

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

-1
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 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.