Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Here's what I'd like to do in pseudocode:

for subdir in [all first-level subdirectories of the current directory]:
    for file in [all files in subdir]:
        rename file to "myprefix_" + current_filename_padded_with_zeroes

What I mean by current_filename_padded_with_zeroes is e.g. if the current filename is 01.png change to 0001.png, or 100.png change it to 0100.png.

Can anyone help me translate the above into a bash script?

Something like... I'm not sure how to do the renaming part:

for DIR in $(ls) 
    for FILENAME in $(ls $DIR)
        mv "$FILENAME" "myprefix_{%FILENAME}"   
share|improve this question

Use the following to rename all files in the current directory:

for file in * ; do
    mv "$file" "myprefix_$( printf "%04d" $file )"

The printf program is similar to the function of the same name in quite a few programming languages.

You need to use basename and dirname to make it work from a different directory.

share|improve this answer

Use printf to pad zeros until it matches the length you want. %04d means filling zeros to a length of 4 digits (if your number is >= 4 digits, it won't change anything). ${a%.png} matches the part of $a before .png. Some basename and dirname is required to extract the actual filename from the path and reconcatenate it.

You can replace the loop using find . -dept 2.

find . -depth 2 -exec bash -c 'FILENAME=`basename {}`; mv {} `printf \`dirname {}\`/%04d.png ${FILENAME%.png}`'  \;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.