2

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

2 Answers 2

2

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.

1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .