Search code examples
bashmacosshellfilerenaming

Renaming files in Shell script for loop


I run OS X and have multiple photos and started naming them xyz-100.jpg, xyz-101.jpg, xyz-102.jpg up to xyz-402.jpg and now want to rename them by basically reducing the number by 99, making it xyz-1.jpg, xyz-2.jpg up to xyz-303.jpg.

I know I can use the mv command for that, but I don't seem to be able to implement a variable into the filename, such as xyz-$reduced.jpg. How can I properly do that?


Solution

  • I strongly recommend you move them to another directory, since otherwise you run the risk of confusion if something bad happens midway through. So try:

    mkdir tmp
    for ((n=100; n<=402; n++)); do 
      ln xyz-$n.jpg tmp/xyz-$((n-99)).jpg
    done
    

    That should give you the files you want inside tmp/. Then you can move that directory where you'd like and remove the old files. If you're not familiar with ln, think of it as half of a mv. Basically mv foo bar is the same as ln foo bar; rm foo. By linking the newly named files in a subdirectory, you won't have any conflicts trying to figure out if file 150 is really 150 or if it is the renamed 249. Also, instead of iterating through the existing files and trying to parse the number, just use jot to generate the names that you know you want.