Home > Back-end >  printing output of ls | wc -l in a txt file with two columns
printing output of ls | wc -l in a txt file with two columns

Time:04-30

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.

CodePudding user response:

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) >> output.txt
 done

CodePudding user response:

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 e.g. 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
  • Related