5

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?

2
  • What do you want achieve? Asking because youre creating the $output_dir but not using it (it remains as an empty dir). Commented Mar 27, 2017 at 9:48
  • @jm666 i am doing some other running of scripts that i have omitted... Commented Mar 27, 2017 at 9:59

3 Answers 3

6

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 \; 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, this is working, however i added an update, which is trying to find the files with the same pattern, but again we need those three digit pattern. how can I do it? could you please update your answer? thanks
Hi. The above solves my issue but the solution seems overly complicated. Is there a simpler syntax?? tr -s ' ' < file_V$(printf "%02d" $i).txt > file_V$(printf "%02d" $((++i))).txt. thanks!!!
1

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" 

2 Comments

then my variables are not resolved... when later i use these variables, the reference is not clear... missing.
Right after these printf command, examine variables using declare -p input_dir output_dir command and see what it prints.
0

Other way - try this:

export count=12 export ZEROS=0000 echo "file${ZEROS:${#count}}${count}" 

out:

file0012 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.