Skip to main content

wc -l to count lines all txt files in folders and subfolders [Resolved]

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.


Question Credit: SciGuy
Question Reference
Asked May 24, 2019
Tags:
Posted Under: Unix Linux
6 views
3 Answers

find /the/path/to/search/ -name "*.txt" -exec wc -l {} \;

credit: Jeff Schaller
Answered May 24, 2019

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.


credit: Jeff Schaller
Answered May 24, 2019
find /yourpath -type f -name "*.txt" -exec wc -l {} /dev/null \;

credit: Jeff Schaller
Answered May 24, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA