No announcement yet.

Count Number Of Files In A Directory And Its Size

  • Filter
  • Time
  • Show
Clear All
new posts

  • Count Number Of Files In A Directory And Its Size

    To find a folder's size?

    A directory ("folder", if you like) is a file like all the others, just a somewhat "special" one. It's own size is rather small, but if you'd like to know the size of all of it's contents (recursively), you can use 'du':

    du /path/to/directory
    du testdir

    That prints

    10264 testdir/

    or in human-readable form:

    du -h testdir

    that prints

    11M testdir

    Now i wanted to count the number of files in the targetdir directory.

    $ ls -1 targetdir | wc -l
    The above command reads ls dash one piped to wc dash letter l.

    Note that if you had used ls dash letter l instead, the count is one greater than the actual number of files. This is because ls dash letter l outputs an extra total line:

    $ ls -1 targetdir

    The above method will count symbolic links as well as subdirectories in targetdir (but not recursively into subdirectories).

    If you want to exclude subdirectories, you need a heavier duty tool than ls.

    $ find targetdir -type f  -maxdepth 1 | wc -l

    -type f ensures that the find command only returns regular files for counting (no subdirectories).

    By default, the find command traverses into subdirectories for searching. -maxdepth 1 prevents find from traversing into subdirectories. If you do want to count files in the subdirectories, just remove -maxdepth 1 from the command line.

    Note that the find command does NOT classify a symbolic link as a regular file. Therefore, the above find -type f command does not return symbolic links. As a result, the final count excludes all symbolic links.

    To include symbolic links, add the -follow option to find.

    $ find targetdir -type f -follow  -maxdepth 1 | wc -l

  • #2
    Thanks for your sharing, it was great for me
    Friv5 Friv2 Friv20