Search code examples
bashxargs

How can I use wc for each file returned by ls


I am trying to get the following information, given a folder with a lot of folders, get the name of each one with the total number of subfolders without recursivity, in order to do it fast.

To do this i am triying:

ls -d */ | xargs ls | wc -l

This of course sum all xargs ls, the problem is that I don't know how to split

100000

The second try is

for i in ls -d */; do echo $i; ls $i | wc -l; done

but returns

name folder
wc result
name folder
wc result
name folder
wc result

returned by that command instead of

folder_a    1000
folder_b    10
folder_c    10
...

is it possible to do this in one line or do I need to create a bash script?

Thanks


Solution

  • Like this:

    printf '%s\n' */ |
        while IFS= read -r dir; do
            res=$(printf '%s\n' "$dir"* | wc -l)
            echo "$res $dir"
        done