0

I have a image directory with many more subdirectories that contain images with, let's say random, filenames.

images/black-shoe/gsafdfs.jpg
images/black-shoe/ggdfgdf.jpg
images/black-shoe/gdfgd3f.jpg
images/black-shoe/g4twegd.jpg

images/red-shoe/ggsdgdfs.jpg
images/red-shoe/gskjhkhf.jpg
images/red-shoe/gsakytfs.jpg

And I want to batch rename all images to their parent directory but to prevent one overwriting the other, add a suffix like so.

images/black-shoe/black-shoe-1.jpg
images/black-shoe/black-shoe-2.jpg
images/black-shoe/black-shoe-3.jpg
images/black-shoe/black-shoe-4.jpg

images/red-shoe/red-shoe-1.jpg
images/red-shoe/red-shoe-2.jpg
images/red-shoe/red-shoe-3.jpg

I use Debian 8 and am familiar with using the command line. Ideally I'd like small script or oneliner that I can execute from within images/ to apply them on all sub dirs at once.

  • Please note that superuser.com is not a free script/code writing service. If you tell us what you have tried so far (include the scripts/code you are already using) and where you are stuck then we can try to help with specific problems. You should also read How do I ask a good question?. – DavidPostill Nov 21 '16 at 10:32
0

This short script should do the trick (files and directories names may contain spaces): (should be called with basedir as parameter)

#!/bin/bash

basedir=$1

while IFS= read -r -d '' path; 
do 
  dirn=$(basename "$path")
  echo "===> $path"
  let i=1
  while IFS= read -r -d '' fname; 
  do
    fext=$(echo "$fname" | awk -F '.' '{print $NF}')
    mv "$fname" "${path}/${dirn}-${i}.${fext}"
    let i=i+1
  done < <(find "$path" -maxdepth 1 -type f -print0)
done < <(find "$basedir" -type d -print0)
  • Thanks. This seems to work but it also rename the script itself to '.-1.sh' – johnny538 Dec 7 '16 at 19:54
  • also, each time I run it, 1 file seems to get deleted. – johnny538 Dec 7 '16 at 20:21
  • Hi, the script itself was not intended to be inside the directory structure where files get renamed, it should be stored somewhere else. But some additional clause could be added to rename just 'jpg' files for example. – tonioc Dec 9 '16 at 8:43

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.