Search code examples
linuxbashcygwin

Linux box, counting files each subfolder in directory


I already have this line for Linux box.

find . -type f -name '*.txt' -exec ls -l {} \;

It's getting all the TXT files in directory. But what I can't do and what I want to do is, to read all the .txt files on subfolder in one directory.

For example : ParentTxtFolder --> ChildTxtFolder --> Txtfolder1, Txtfolder2, Txtfolder3. Per one Txtfolder it contains .txt files.

So what I want is, to scan Txtfolder1 and count .txtfiles.

If this output is possible, Expected output :

Txtfolder1 - 14
Txtfolder2 - 10
Txtfolder3 - 18

I'm really stuck on this one. Thanks in advance!


Solution

  • One way you can do it is like this:

    for d in `find . -type d` ; do echo -n "$d: " ; find "$d" -type f -depth 1 -name \*.txt | wc -l ; done
    

    or less succinctly:

    for d in `find . -type d`   # for each directory
      do
        echo -n "$d: "          # print directory name
        find "$d" -type f -depth 1 -name \*.txt | wc -l
      done                      # followed by count of .txt files in directory