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

  • are you worried at all about collisions of the new names?
    – Jeff Schaller
    Jun 10, 2019 at 16:05
  • No they are unique and files with the same name already end in mp4001.jpg mp4002.jpg etc
    – Teddy77
    Jun 10, 2019 at 16:10

1 Answer 1


With bash, you could do this:

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

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// /-}
  • 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.
    – Teddy77
    Jun 10, 2019 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, 2019 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.