Search code examples
bashnumberspaddingzerodigits

bash add leading zeros to the count while number


I have the bash while loop using an initial count. I want to add %03d three digits to the count so that the output is like:

folder001
folder002

my code is:

    #!/bin/bash

    input_file=$1
    csv_file=$2

    count=1
    while IFS= read -r line || [[ -n "$line" ]]; do
      input_dir="./res/folder"%03d"$count/input"
      output_dir="./res/folder"%03d"$count/output"
      results_dir="./res/all_results_png/png"

      mkdir -p "$input_dir" "$output_dir"
      printf '%s\n' "$line" > "$input_dir/myline.csv"
      find $output_dir -name image_"folder$count*".png -exec cp {} $results_dir \;

      ((count++))
    done < "$csv_file"

i add %03d to the code above as you can see, but it is printing it literally. what am I missing here? thanks

upadte

added an update which is: trying to do a find of the files with the pattern

image_"folder$count*".png

how can I reflect the three digits changes in the find command as well?


Solution

  • You can use printf to achieve this. Here's an example:

    AMD$ cat File.sh
    #!/bin/bash
    
    count=25
    input_dir=$(printf "/res/folder%03d/input" $count)
    echo $input_dir
    
    AMD$ ./File.sh
    /res/folder025/input
    

    For the update in your question, you can do the same logic.

    filename=$(printf "image_folder%03d" $count)
    find . -name "$filename.png"
    

    In your case:

    find $output_dir -name "$filename.png" -exec cp {} $results_dir \;