1

I'd like to count the number of files in each folder. For one folder, I can do it with:

find ./folder1/ -type f | wc -l

I can repeat this command for every folder (folder2, folder3, ...), but I'd like to know if it is possible to get the information with one command. The output should look like this:

folder1 13
folder2 4
folder3 1254
folder4 327
folder5 2145

I can get the list of my folders with:

find . -maxdepth 1 -type d

which returns:

./folder1
./folder2
./folder3
./folder4
./folder5

Then, I thought about combining this command with the first one, but I don't know exactly how. Maybe with "-exec" or "xargs"?

Many thanks in advance.

1 Answer 1

2

A possible solution using xargs is to use the -I option, which replaces occurrences of replace-str (% in the code sample below) in the initial-arguments with names read from standard input:

find . -maxdepth 1 -type d -print0 | xargs -0 -I% sh -c 'echo -n "%: "; find "%" -type f | wc -l'

You also need to pass the find command to sh if you want to pipe it with wc, otherwise wc will count files in all directories.

Another solution (maybe less cryptic) is to use a one-liner for loop:

for d in */; do echo -n "$d: "; find "$d" -type f | wc -l; done
Sign up to request clarification or add additional context in comments.

3 Comments

Many thanks! My folders are not named "folder1", "folder2", etc. That was for the example. Then, I'm trying to adapt the command line such as: for d in $(find . -maxdepth 1 -type d); do echo -n "$d: "; find $d -type f | wc -l; done My problem is that some of my folders have spaces in their name and I don't know how to deal with that...
I've managed to deal with my problem of spaces doing: for d in $(find . -maxdepth 1 -type d | sed "s/ /99space99/"); do echo -n "${d//99space99/ }: "; find "${d//99space99/ }" -type f | wc -l; done. That works but it's quite ugly...
I edited the answer to take care of directories with spaces. For the version with xargs, just use a combination of print0 and -0 options. In this case, the separator will be the NULL character and not the space. The second version relies on Bash expansion to quote the directories. It will not work with hidden directories however. You can also change the value of the $IFS variable: see this post stackoverflow.com/questions/4895484/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.