Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading