I need to rename all image files in a directory, and name them whatever the folder they are in is called... Is this possible using a Bash script?

I also need to number them (0001.jpg, 0002.jpg, 0003.jpg, ect...) consecutively. The problem I'm having is that there are some jumps between the numbers.. (0018.jpg, 0019.jpg, 0025.jpg, 0026.jpg, ect...) I'd like to rename the 0025.jpg to be 0020.jpg and the 0026.jpg to be 0021.jpg ect...


Yes, it's possible. You can use find /search/path -type d to find all dirs and use -exec option to exec some actions with directory path as parameter. And you can have bash script which runs NUM=0; for file in /path/to/folder/*.jpg; do mv file NUM.jpg; let "NUM=NUM+1"; done; or something like this


To use this command you have to be in the directory where the .jpg files are or you have to customize the command a little bit.

 let a=0; for i in *.jpg; do let a=a+1; b=`basename $PWD`; c=`printf %04d$b.jpg $a`; mv $i $c; done

The output will look like:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.