JohD
JohD

Reputation: 25

Recursively rename image collection with subfolders

I'm trying to rename files in a huge folder of images, that contains lots of subfolders and within them images.

Something like this:

ImageCollection/
    January/
      Movies/
        123123.jpg
        asd.jpg
      Landscapes/
        qweqas.jpg
    February/
      Movies/
        ABC.jpg
        QWY.jpg
     Landscapes/
        t.jpg

And I want to run the script and rename them in ascending order but keeping them in their corresponding folder, like this:

ImageCollection/
    January/
      Movies/
        0.jpg
        1.jpg
      Landscapes/
        2.jpg
    February/
      Movies/
        3.jpg
        4.jpg
     Landscapes/
        5.jpg

Until now I have the following:

#!/usr/bin/env bash
x=0
for i path/to/dir/*/*.jpg; do
    new=$(printf path/to/dir/%d ${x})
    mv ${i} ${new}
let x=x+1
done

But my problem, relies on not being able to keep the files in their corresponding subfolders, instead everything is moved to the path/to/dir root folder.

Upvotes: 1

Views: 297

Answers (2)

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

A pure Bash solution (except from the mv, of course):

#!/bin/bash

shopt -s nullglob

### Optional: if you also want the .JPG (uppercase) files
# shopt -s nocaseglob

i=1
for file in ImageCollection/*/*.jpg; do
    dirname=${file%/*}
    newfile=$dirname/$i.jpg
    echo mv "$file" "$newfile" && ((++i))
done

This will not perform the renaming, only show what's going to happen. Remove the echo if your happy with the result you see.

You can use the -n option to mv too, so as to not overwrite existing files. (I would definitely use it in this case!). If -n is not available, you may use:

[[ ! -e $newfile ]] && mv "$file" "$newfile" && ((++i))

This is 100% safe regarding filenames (or dirnames) containing spaces or other funny symbols.

Upvotes: 1

AKS
AKS

Reputation: 17326

#!/bin/bash

x=0
for f in `find path_to_main_dir_or_top_folder | grep "\.jpg$"`;
do
   mv $f $(dirname $f)/$x.jpg && ((x++))
done
echo shenzi
  1. $f will hold all files with full path for all *.jpg files
  2. dirname command will give you the fill path (excluding the filename) for a given $f file.
  3. $x.jpg will do the trick. $x value will increment per iteration in the loop.

Upvotes: 0

Related Questions