用bash腳本批量修改文件名稱(二)

前言:在上一篇文章中,我使用了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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容