hans

hans

【Shell】Rename all files in a certain directory, with five digits and leading zeros.


I have only been exposed to shell for a short time, so I can't write complex scripts. I can only make do with some simple ones that can achieve the functionality I want. I'll learn slowly!

The functionality of this script is roughly as follows: first, enter a directory that contains many subdirectories. Then, enter each subdirectory one by one and rename all the jpg images in the subdirectory to a five-digit number with leading zeros. Because I couldn't find a direct way to output a five-digit number online, I had to define a seven-digit number "num". After renaming is complete, I replace the leading "100" with "0" (there are only a few thousand files in my subdirectories). This can be applied in various situations.

#!/bin/sh

cd train/
num=1000000
new=0
for dir_name in $(ls) # search subdirectories
do
    l=1
    if [ -d $dir_name ]; then
        cd $dir_name/ # enter subdirectory
        for img in $(ls)
        do
            let new=num+l
            rename "s/$img/$new.jpg/" *
            let l=l+1
        done;
        rename 's/^100/0/' *.jpg
        cd ../
    fi
done;

If anyone has a better method, I hope you can share it in the comments. Thank you!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.