Find the answer to your Linux question:
Results 1 to 2 of 2
Hi all. I want to count the number of files in each sub folder of a directory structure. At the moment I can do: ls -1R /Folder | wc -l ...
  1. #1
    Just Joined!
    Join Date
    Sep 2009
    Posts
    4

    Count the files for each sub folder?

    Hi all.

    I want to count the number of files in each sub folder of a directory structure.

    At the moment I can do:

    ls -1R /Folder | wc -l

    Which lists the item count for all the folders as one. I can do:

    ls -1R /Folder wc –l

    Which lists all the folders in the top level and all the items.

    Is there any way to get the list of folders and then item count for each folder?

    Thanks

  2. #2
    Just Joined!
    Join Date
    Dec 2009
    Location
    California
    Posts
    68
    Sounds like a bit of a homework question.....
    But I'll give you the general method.
    You are right about wanting to get a list of the folders, then for each one, couting the items in that folder.

    First, you'd want to get a list of the contents of the current directory and write this to a file:

    ls >/tmp/filelist

    Now, go through each item in that file and see if its a directory. If it is, write it to a file:

    cat /tmp/filelist |while read fname
    do
    if [ -d $fname ]
    then
    echo $fname
    fi
    done >/tmp/dirlist

    Now, you'd want to go through the directory list and count the contents of each one. Use the same "while" construct as above, only read the contents of dirlist. Also, you won't need an "if" inside.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...