Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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:

#!/bin/bash
for DIR in $(ls) 
do
    for FILENAME in $(ls $DIR)
        do
        mv "$FILENAME" "myprefix_{%FILENAME}"   
        done
done
share|improve this question
add comment

2 Answers

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

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

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
add comment

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
add comment

Your Answer

 
discard

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.