前言:在上一篇文章中,我使用了warp模擬終端,讓它教我寫(xiě)bash腳本來(lái)批量修改文件文稱。這一篇?jiǎng)t是優(yōu)化,在保留文件擴(kuò)展名的同時(shí);根據(jù)文件數(shù)量,設(shè)置新文件名的對(duì)齊位(也就是有幾十個(gè)文件時(shí),從01開(kāi)始編號(hào);幾百個(gè)文件時(shí),則是從001開(kāi)始。);并且可以選擇是否添加前綴。
執(zhí)行時(shí)輸入“./rename.sh /path/files optional_prefix”即可,如果不需要前綴,最后一個(gè)參數(shù)改成noprefix即可。代碼如下:
#!/bin/bash
# Change the file name accroding to the original order by digits
# while preserving the file extension.
# Check before running: Need 3 arguments to run the script properly
if [[ $# -lt 2 ]]; then
echo "Didn't run, because the number of argument needs to be 2"
echo "EX: $0 [/path/to/file] [new_name_prefix]"
exit 0
fi
# 1. Get the old name files's directory and enter it
directory=$1
cd "$1"
# 2. Set the new name prefix
prefix=$2
# 3. Count the number of files in the directory
file_count=$(($(ls -l | grep -v '^d' | wc -l) -1))
echo "The total number of files to change name is $file_count."
# 4. Get the length of file_count
bits=${#file_count}
echo "The aligned number of the new name would be $bits."
# 5. Set the starting number
starting_number=1
# 6. Change to the new file name
if [ "$2" = "noprefix" ]; then
# Loop through each file in the directory and rename without prefix
for file in "$directory"/*; do
# Get the current file name (basename is a command in shell)
current_name=$(basename "$file")
# Get the file extension
extension="${current_name##*.}"
# Generate the new file name
new_name="$(printf "%0${bits}d" "$starting_number").${extension}"
# Rename the file
mv "$file" "$directory/$new_name"
((starting_number++))
done
else
# Loop through each file in the directory and rename with prefix
for file in "$directory"/*; do
# Get the current file name
current_name=$(basename "$file")
# Get the file extension
extension="${current_name##*.}"
# Generate the new file name
new_name="${prefix}-$(printf "%0${bits}d" "$starting_number").${extension}"
# Rename the file
mv "$file" "$directory/$new_name"
((starting_number++))
done
fi
echo "Complete. And the first 10 file is: $(ls | head -10)"
exit 0