编写 bash 脚本以在当前目录和子目录中按顺序重命名文件

Writing a bash script to rename files sequentially in current directory and sub-directories

如何修复此脚本,使其使用用户输入的字符串重命名当前目录中的所有文件以及子目录中的所有文件?

当前文件名可以是任何名称。我希望所有文件的最终结果都被称为 STRING_001.jpg STRING_002.jpg STRING_003.jpg 等...

如果文件在各自的目录中仅按顺序排列,或者文件编号是否转移到下一个目录,对我来说都没有关系。

经过几个小时的研究,这是我最终编写的代码:

#!/bin/bash

# Let user input a string to use in filenames
read -p "Enter filename: " STRING

# Variable for sequential filenames
n=0

files=(./*)

# Looks for files in current directory
if [ ${#files[@]} -gt 0 ]; 
then
        for f in ./*; do
                  # Renames files with STRING and sequentially
                printf -v num %03d "$((++i))"
                mv "$f" "${STRING}_$num.jpg" 
        done
else 
        for d in *; do
        ( cd -- "$d" && 
                for f in ./*; do 
                          # Executes rename command in sub-directories
                        printf -v num %03d "$((++i))"
                        mv "$f" "${STRING}_$num.jpg" 
                done 
        )
done;
fi

脚本:

#!/bin/bash
read -p "Enter filename: " STRING
find . -type f | cat -n - | while read num infile ; do
    filename=$(basename "${infile}")
    filesans="${filename%%.*}"
    newname=$(printf '%s_%03d' "${STRING}" "${num}")
    newfile="${infile/$filesans/$newname}"
    echo "mv \"${infile}\" \"${newfile}\""
done

(这里,这个脚本被命名为62566825.sh。不是最伟大的名字。)

设置目录:

mkdir dir1 dir2 dir3
touch dir1/file{1,2,3} dir2/file{4,5,6}.jpg dir3/file{7,8,9}.foo.gz

$ find . -type f
./62566825.sh
./dir1/file1
./dir1/file2
./dir1/file3
./dir2/file4.jpg
./dir2/file5.jpg
./dir2/file6.jpg
./dir3/file7.foo.gz
./dir3/file8.foo.gz
./dir3/file9.foo.gz

执行:

$ ./62566825.sh
Enter filename: QUUX
mv "./62566825.sh" "./QUUX_001.sh"
mv "./dir1/file1" "./dir1/QUUX_002"
mv "./dir1/file2" "./dir1/QUUX_003"
mv "./dir1/file3" "./dir1/QUUX_004"
mv "./dir2/file4.jpg" "./dir2/QUUX_005.jpg"
mv "./dir2/file5.jpg" "./dir2/QUUX_006.jpg"
mv "./dir2/file6.jpg" "./dir2/QUUX_007.jpg"
mv "./dir3/file7.foo.gz" "./dir3/QUUX_008.foo.gz"
mv "./dir3/file8.foo.gz" "./dir3/QUUX_009.foo.gz"
mv "./dir3/file9.foo.gz" "./dir3/QUUX_010.foo.gz"

(只需修复 echo "mv 即可实际执行某些操作。)