简体   繁体   中英

printing output of ls | wc -l in a txt file with two columns

I have many directories with different number of CSV files in each of them. I am interested in getting a list of those directories with a their respective number of CSV files. So I have this bash loop.

 for i in 21 22 23
do
ls my/directory/name$i/*csv | wc -l
done

The question is, how do I get a txt file with an output like this?
 name21 3
name22 5
name23 2

Where the 1st column corresponds to the name of each directory and the second one corresponds to the number of CSV files in each directory.

You can echo the names and results of your command to output.txt :

for i in 21 22 23
 do
   echo name$i  $(ls my/directory/name$i/*csv | wc -l)
 done > output.txt

https://mywiki.wooledge.org/ParsingLs explains a number of scenarios where using ls and parsing its output will produce wrong or unexpected results. You are much better off eg using an array and counting the number of elements in it.

for i in 21 22 23; do
   files=( my/directory/name$i/*csv )
   echo "name$i ${#files[@]}"
done >output.txt

Perhaps also notice the redirection after done , which avoids opening and closing the same file repeatedly inside the loop.

If you want to be portable to POSIX sh which doesn't have arrays, try a function.

count () {
    echo "$#"
}

for i in 21 22 23; do
    echo "name$i $(count my/directory/name$i/*csv)"
done >output.txt

For a robustness test, try creating files with problematic names like

touch my/directory/name21/"file name
with newline".csv my/directory/name22/'*'.csv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM