rename files in sub directories

76 Views Asked by At

I am running the fallowing script to rename files numerical with in all sub directories and sub directories.

num=1   
echo "Enter the file path"
read -r path 
cd $path 
for file in $path/*.tif; do
       mv -v "${file}" "$path/$(printf "%04d" ${num}).tif"
       num=$(( ${num} + 1 ))
done

when I run the script it only runs on the root dir and not the sub directories as well? What can I add or is there a different way to write the script?

1

There are 1 best solutions below

14
Gilles Quénot On

What I would do:

num=1   
echo "Enter the file path"
read -r path 
shopt -s globstar # enable recursion **
cd "$path" 
for file in $path/**/*.tif; do
       mv -v "$file" "$path/$(printf "%04d" $num.tif)"
       ((num++))
done

Or using Perl's rename:

shopt -s globstar
rename -n 's/.*/sprintf "%04d%s", ++$::c, ".tif"/e' ./$path/**/*.tif

Remove -n switch, aka dry-run when your attempts are satisfactory to rename for real.