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}"   

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.


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}`'  \;

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.