Bash

批量重命名“案例重複”

  • November 7, 2019

關於這個問題和答案:https ://unix.stackexchange.com/a/188020/189709

for f in *; do mv --backup=numbered -- "$f" "${f,,}"; done
rename -v -- 's/\.~(\d+)~/$1/' *.~*~

mv:此命令隱式地將所有文件名更改為小寫。如何修改選項不這樣做?備份編號足以區分文件。

rename: test.~1~ 如果文件 test1 已經存在,則不會重命名。如何更改選項以使 test.~1~ 重命名為 test2?

您可能希望自己實現重命名策略,因為您正在查看的程式碼將呼叫中的文件名顯式小寫mv以擷取實際文件名衝突中的重複項。

以下僅在存在衝突時重命名文件,而不會實際導致衝突(即它不會退回到 GNUmv來處理衝突):

#!/bin/bash

# The suffix array contains a filename suffix (a positive integer)
# for each lower-cased filename.
declare -A suffix

# Get all names in the current directory.
set -- *

# Initialise the suffixes for each existing name to zero.
for name do
       suffix[${name,,}]=0
done

for name do

       # Loop until no name collision.
       while true; do
               # Get the current suffix for this filename.
               suf=${suffix[${name,,}]}

               # Increment the suffix for this filename.
               suffix[${name,,}]=$(( ${suffix[${name,,}]} + 1 ))

               # If the suffix is 0, empty it.
               [[ $suf == 0 ]] && suf=

               # Create the new name.
               newname=$name$suf

               # Break out of the loop if the name didn't change, or if
               # there's no other file that has this name.
               if [[ $name == "$newname" ]] ||
                  [[ -z ${suffix[${newname,,}]} ]]
               then
                       break
               fi
       done

       if [[ $name != "$newname" ]]; then
               printf '%s --> %s\n' "$name" "$newname"
               # uncomment the next line to actually do the renaming
               # mv -- "$name" "$newname"
       else
               printf '%s unchanged\n' "$name"
       fi

done

(注意註釋掉的mv,你可能想用註釋掉的那一行來執行它,直到你確信它做了正確的事情)

測試:

$ ls
A         Bb        TEST1     a         bb        test
BB        TEST      Test      bB        script.sh
$ bash script.sh
A unchanged
BB unchanged
Bb --> Bb1
TEST unchanged
TEST1 unchanged
Test --> Test2
a --> a1
bB --> bB2
bb --> bb3
script.sh unchanged
test --> test3

引用自:https://unix.stackexchange.com/questions/550858