如果名稱與特定模式匹配,我需要批量重命名檔案串列,該模式以 1 個或多個數字開頭,后跟下劃線,然后是字母數字。例如:“123_ABC123.txt”(擴展名可以是任何東西,不一定是'txt')。
我認為正則運算式看起來像這樣:
\d _*.*
但我不確定如何在 Unix 中實作這一點,具體來說,我如何表達第一部分\d (*
謝謝!
uj5u.com熱心網友回復:
使用您顯示的示例,請在純 BASH 中嘗試以下解決方案。
mv一旦您對此感到滿意,這將列印(重命名)命令,然后您可以使用實際代碼重命名檔案。
for file in [0-9]*.*
do
firstPart=${file%%_*}
secondPart1=${file%.*}
secondPart=${secondPart1#*_}
extension=${file##*.}
echo "File $file will be renamed to: ${secondPart}_${firstPart}.${extension}"
echo "mv \"$file\" " "\"${secondPart}_${firstPart}.${extension}\""
done
顯示的檔案名為的輸出123_ABC123.txt將如下所示:
File 123_ABC123.txt will be renamed to: ABC123_123.txt
mv "123_ABC123.txt" "ABC123_123.txt"
注意:一旦您對上述代碼的結果感到滿意,然后運行以下代碼以實際重命名檔案:
for file in [0-9]*.*
do
firstPart=${val%%_*}
secondPart1=${val%.*}
secondPart=${secondPart1#*_}
extension=${val##*.}
echo "File $file will be renamed to: ${secondPart}_${firstPart}.${extension}"
mv "$file" "${secondPart}_${firstPart}.${extension}"
done
uj5u.com熱心網友回復:
你可以使用這個rename命令:
rename -n 's/^(\d )_(. )(\.[^.] )$/$2_$1$3/' [0-9]*.*
123_ABC123.txt' would be renamed to 'ABC123_123.txt'
一旦滿意,您可以洗掉-n(試運行)選項。
解釋:
^(\d ): 在捕獲組 #1 的開頭匹配 1 個數字_: 匹配一個_(. ): 匹配捕獲組 #2 中任意字符的 1(\.[^.] )$:匹配點和擴展名以在行結束前捕獲組#3$2_$1$3_:在捕獲組 2 和 1 之間插入并保留擴展名$3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482064.html
