I want an output similar to this,to show how many files and eventually subdirs are contained in directories. The output can be similar to this one

dir1 100
dir2/dir3 240
dir3 12
dir5 44

Which app,script can make this?

closed as unclear what you're asking by G-Man, cas, Jeff Schaller, maulinglawns, Rui F Ribeiro Jan 29 '18 at 2:18

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • What about subdirectories? – Jeff Schaller Jan 28 '18 at 13:59
  • Forgot..and subdirs too.Edited now – elbarna Jan 28 '18 at 17:40

If you have GNU find, you can do:

find /path/to/directory -type f -printf "%h\n" | uniq -c

For example:

$ find /etc/skel /etc/profile.d /etc/resolvconf -type f -printf "%h\n" | uniq -c 
     10 /etc/profile.d
      1 /etc/resolvconf
      2 /etc/resolvconf/resolv.conf.d
      1 /etc/resolvconf/update.d
      1 /etc/resolvconf/update-libc.d
      6 /etc/skel

%h prints the directory name of the matched file, so, after that it's a simple matter of getting uniq to count the number of times the foldername was duplicated.

  • find works recursively, so it will display how many files are contained in the /path/to/directory directory as well as all its directories. – Georgi Tsvetanov Tsenov Jan 28 '18 at 17:42
  • 1
    @Georgi yes, that's right. But no file will be counted more then once. – roaima Jan 29 '18 at 0:42
  • 1
    @GeorgiTsvetanovTsenov yes, but here, for each file it's only printing its immediate parent directory, so the count given for each directory is only for files in it, not in subdirectories. But subdirectories are recursively listed. – Olorin Jan 29 '18 at 1:24

Found a solution

du -a | cut -d/ -f2 | sort | uniq -c | sort -nr

From this site

Output is

 31 dir2
  2 dir3
  1 dir4    

This will count files in directories for you starting at .. You can provide a starting path to the first find if you want:

find -type d -exec bash -c 'printf "%s %d\n" "{}" $(find "{}" -maxdepth 1 -type f | wc -l)' \;

It works by descending the tree of directories (from . or from an explicit path that you might provide) and calling the bash -c '...' snippet for each. This snippet prints the directory pathname and the the number of files it contains.

Here's sample output from /etc

/etc 27
/etc/alternatives 1
/etc/bash_completion.d 6
/etc/dbus-1 2
/etc/defaults 0
/etc/defaults/etc 16
/etc/defaults/etc/freetds 3
/etc/defaults/etc/inetd.d 1
/etc/defaults/etc/my.cnf.d 4
/etc/defaults/etc/pki 0
/etc/defaults/etc/pki/ca-trust 1
/etc/defaults/etc/profile.d 5

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