0

I have a folder on my desktop named Models. In the folder, there are named folders with jpeg files without the .jpg extensions. The jpeg file names are random hashes. I would like to use a bash script to batch rename these jpeg files to their directory names with increments and append the .jpg extension on each file.

It's basically something like

Models/

 Alice/
      a5ccB2ff3e
      ee420bc4a
      2acee54dc
      ...
 Alex/
      de33fa24c0
      d1eaa48e0a
      ...

And I want to to be like

Models/

 Alice/
      Alice001.jpg
      Alice002.jpg
      Alice003.jpg
      ...

 Alex/
      Alex001.jpg
      Alex002.jpg
      ...
2
  • 1
    Please show us, what have you tried so far
    – mrc02_kr
    Nov 18, 2018 at 7:01
  • I don't even know how to do a sub directory search. Trying to show what I tried would just be toying. I would try in php but bash is a different language.
    – Boygee
    Nov 18, 2018 at 7:17

2 Answers 2

0

From the description of your question I am assuming that total no. of files in a folder does not exceed 999.

This is a simple bash script run it in your top directory i.e Models:

#!/bin/bash
for i in ./*
do
if [ -d "$i" ]
then
j=001
for k in "$i"/*
do
mv "$k" "$i"/"$i""$j".jpg
j=${j#0}
if [ ${j:0:1} -eq 0 ]
then 
j=${j#0}
fi
(( j++ ))
j=`printf '%03i' $j`
done
fi
done

It will first check every file in Models, whether it is a directory or not by if [ -d "$i" ] . Then for each file in this directory it will change their names by mv "$k" "$i"/"$i""$j".jpg. And

j=${j#0}
if [ ${j:0:1} -eq 0 ]
then 
j=${j#0}
fi

Above code will remove all the zeroes from beginning so that you will not get the error like:

 ((: 008: value too great for base (error token is "008")
 printf: 008: invalid octal number

And

j=`printf '%03i' $j`

will make value of j 3 digits long.

2
  • It worked partially but threw an error. It only renamed 8 pictures in each folder and deleted the rest (I have backup, don't worry). Then it printed this in the console: /home/myName/Desktop/for.sh: line 13: ((: 008: value too great for base (error token is "008")
    – Boygee
    Nov 18, 2018 at 8:35
  • @Boygee updated answer.
    – Prvt_Yadav
    Nov 18, 2018 at 9:39
0

Try also this simplified version of Debian_yadav's proposal:

for i in *
  do    if [ -d "$i" ] && cd "$i"
          then  j=0
                for k in *
                  do    ((j++))
                        echo mv "$k" $(printf "%s%03d.jpg" $i $j )
                  done
                cd ..
          fi
  done

The echo is for debugging only; remove if happy with what you see.

It cds into each directory available, resets the counter, loops across all target files, increments the counter for each, and the does the rename.

You must log in to answer this question.

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