Search code examples
bashfor-loopleading-zero

bash get the number of files and pass it to for loop


I am trying to get the number of files with a certain pattern in a directory and then do a for loop starting from zero to that number.

number=`ls -d *pattern_* | wc -l`%3d
for i in {001.."$number"};do
  # do something with $i
done

the problem is that my numbers are three digits, so that is why i added %3d to the end of my number variable, but it is not working.

so if I have 20 files, the number variable in the for loop should get a leading zero 020.


Solution

  • You really shouldn't rely on the output of ls in this way, since you can have filenames with embedded spaces, newlines and so on.

    Thankfully there's a way to do this in a more reliable manner:

    ((i == 0))
    for fspec in *pattern_* ; do
        ((i = i + 1))
        doSomethingWith "$(printf "%03d" $i)"
    done
    

    This loop will run the exact number of times related to the file count regardless of the weirdness of said files. It will also use the correctly formatted (three-digit) argument as requested.