globus999
globus999

Reputation: 11

Padding file names with zeroes recursively in Cygwin

I have a main directory LT which contains other directories at different levels e.g.

Folder1 Folder2 Folder3 Folder4 Folder5 Folder6 etc.

The names of the folders are not relevant (they change all the time).

Inside the folders are files with different extensions but their names are numerical only. Their extensions change and are not relevant e.g 1.* 17.* 956.*

The highest number in the files is 9999.*

What I need to do is to pad all files with zeroes to 4 digits (in place), regardless of where the file is located. This is (from above), I need to get:

0001.* 0017.* 0956.*

I scoured the net and came up with the following code, which works in Cigwin if I am inside of a given folder:

for file in [0-9]*.*;
do
name=${file%.*}
extension=${file##*.}
new_name=`printf %04d.%s ${name} ${extension}`
mv -n $file $new_name
done

Then, I tried to extend the code so that it will execute against all the files in any folder at any level recursively:

for file in $(find -name '[0-9]*.*');
do
name=${file%.*}
extension=${file##*.}
new_name=`printf %04d.%s ${name} ${extension}`
mv -n $file $new_name
done

This does not work with the error (example):

-bash: printf: ./Gesundheit/99: invalid number

I have no idea what am I doing wrong. Help please?

I tried other solutions but none of them work in Cygwin (they are supposed to work in BASH).

Upvotes: 1

Views: 16

Answers (1)

globus999
globus999

Reputation: 11

The final code that works in Cygwin is:

for file in $(find -name '[0-9]*.*');
do
filename=$(basename "$file")
name=${filename%.*}
dir=$(dirname "$file")
extension=${filename##*.}
new_name=`printf %04d.%s ${name} ${extension}`
new_name="$dir/$new_name"
echo $file
echo $new_name
mv -n $file $new_name
done

And yes, the code is an ugly hack. It can be polished a lot. But I don't care at this point as it works. Also, I left the echo statements in just to see what is the code doing during execution. They are not necessary.

Upvotes: 0

Related Questions