0

I have a load of .jpg files in a folder that have non alphabetical characters like ! , ( ) ^ & . and more.

I need to rename the files so that anything that is not A-Z a-z 0-9 is replaced with nothing. Also spaces should be replaced with - the files also end with .mp4$$$.jpg this part needs to remain in tact.

For example if the file is called

ask me anything.mp4001.jpg
ask, me. anything! 2.mp4001.jpg

The files name should be changed to

ask-me-anything.mp4001.jpg
ask-me-anything-2.mp4001.jpg
  • are you worried at all about collisions of the new names? – Jeff Schaller Jun 10 at 16:05
  • No they are unique and files with the same name already end in mp4001.jpg mp4002.jpg etc – Teddy291 Jun 10 at 16:10
0

With bash, you could do this:

for f in *.jpg
do
  if [[ $f =~ ^(.*)(\.mp[[:digit:]]+\.jpg) ]]
  then
    prefix=${BASH_REMATCH[1]}
    suffix=${BASH_REMATCH[2]}
    prefix=${prefix//[^[:alnum:] ]/}
    prefix=${prefix// /-}
    echo mv -- "$f" "${prefix}${suffix}"
  fi
done

This loops over the *.jpg files and tries to match each filename against the pattern: (anything) followed by .mp (one or more digits) .jpg. If the filename matches, we pull it apart for renaming. The suffix contains periods, so we save it off separately in order to strip any periods in the prefix. After stripping out anything that's not an alphanumeric or space, we replace all spaces with dashes. The filename is then reconstructed for the mv command; remove the echo if the results look correct.

If you'd rather keep dashes in the original filenames, swap out the last two prefix assignments for these:

prefix=${prefix// /-}
prefix=${prefix//[^[:alnum:]-]/}
  • This doesn't change the files name it just outputs "mv -- ask, me. anything! 2.mp4001.jpg ask-me-anything-2.mp4001.jpg" I gave the bash script permissions. – Teddy291 Jun 10 at 17:00
  • correct; I was trying to tread carefully to make sure you got what you wanted, thus the remove the echo if the results look correct part :) – Jeff Schaller Jun 10 at 17:19

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.