1

I have multiple directories with multiple files in each:

folder1
   file1.jpg
   file2.jpg
   file3.jpg
folder2
   file1.jpg
   file2.jpg
   file3.jpg

I want to replace like this:

folder1
   0001.jpg
   0002.jpg
   0003.jpg
folder2
   0001.jpg
   0002.jpg
   0003.jpg

My bash script...

start_dir="/path/to/folder/"
find "$start_dir" -name '*.jpg' -type f \
  |sort \
  |while read name; do 
     ((i++))
     mv -i "$name" \
       "$(printf '%s/%04u%s' "$(dirname "$name")" $((i)) "$(basename ".jpg")")"
   done

doing this:

folder1
   0001.jpg
   0002.jpg
   0003.jpg
folder2
   0004.jpg
   0005.jpg
   0005.jpg

How to get that file replace starts with 0001.jpg in each folder?

2 Answers 2

1

Process each subdirectory separately in wrapped loop

start_dir="/tmp/start/"

find "$start_dir" -name '*' -type d \
  |sort \
  |while read folder; do

i=0
find "$folder"  -maxdepth 1  -name '*.jpg' -type f \
  |sort \
  |while read name; do 
     ((i++))
     mv -i "$name" \
       "$(printf '%s/%04u%s' "$(dirname "$name")" $((i)) "$(basename ".jpg")")"
   done

done

From

 ls -R
.:
fold1  fold2

./fold1:
43.jpg  aa.jpg  a.jpg

./fold2:
ba.jpg  bb.jpg  wbb.jpg

to

ls -R
.:
fold1  fold2

./fold1:
0001.jpg  0002.jpg  0003.jpg

./fold2:
0001.jpg  0002.jpg  0003.jpg

Works without collisions

0

Try something like this instead of ((i++))

if [[ $tmpdir == $(dirname $name) ]] ; then
 i=i+1;
else
  i=0;
fi
tmpdir=$(dirname $name)
2
  • Thanks, but im getting syntax error. Im not sure if im doing right :S
    – Samantha
    Apr 12, 2020 at 22:08
  • Please check my edit Apr 13, 2020 at 8:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .