Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash add leading zeros to the count while number

Tags:

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?

like image 904
passion Avatar asked Mar 27 '17 09:03

passion


2 Answers

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 \;
like image 138
Arjun Mathew Dan Avatar answered Sep 21 '22 10:09

Arjun Mathew Dan


You need to use printf to get formatted output. Replace first 2 lines inside while line to this:

printf -v input_dir './res/folder%03d/input' $count
printf -v output_dir '/res/folder%03d/output' $count

If count=3 then above 2 lines will effectively be:

input_dir="./res/folder003/input"
output_dir="./res/folder003/output"
like image 24
anubhava Avatar answered Sep 25 '22 10:09

anubhava