I have a large number of .jpg file that have extraneous data ahead of a file id that i need to have removed to better set up my file structure for a later project. How can I do a batch rename in either command line or Bash (bash is preferable)

Example: A_file_name_f3xe3_1_60113520.jpg - (60113520 being the ID) To Become: 60113520.jpg

All files have underscores before the ID, but there are randomly placed extra underscores elsewhere in the name.


There's a command especially suited for this :

rename -n 's/.*?(\d+.jpg$)/$1/' *.jpg

It's prename on debian and derivated, and it's a perl executable.

Remove -n switch if your test fit your needs.

To make it the default one (still debian and derivated :

 update-alternatives --set rename /usr/bin/prename
  • 1
    Nema wrote that there are randomly placed extra underscores elsewhere in the name, indicating no consistent file name prefix before the ID. – Daniel Beck Dec 20 '12 at 21:16

Use the following:

for FILE in *.jpg ; do mv -v "$FILE" "${FILE//*_/}" ; done

This removes everything in JPG file names up to and including the last underscore in the file name. It is described here in section Substring Replacement:


Replace all matches of $substring with $replacement.

In your case, replacement is empty.

  • this works perfect in my case, but how to make it recursevly? – Kreker Apr 8 '14 at 8:41

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.