Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 一鍵批量重命名:Shell 參數展開實戰

編輯:Linux 系統常見問題解答

需將目錄下所有檔名包含 class 的字串替換為 classbak?一行命令搞定:

for i in $(ls); do mv "$i" "${i/class/classbak}"; done

命令拆解

  • $(ls):列出當前目錄所有檔名(注意:含空格檔名會有問題,建議改用 find 或 for i in *)。
  • ${i/class/classbak}:Bash 參數展開的「模式替換」語法,僅替換第一次出現的 class。
  • 若需全域替換,使用 ${i//class/classbak}(雙斜線)。

更健壯的寫法

# 處理含空格、特殊字元檔名
for f in *; do
    [[ -e "$f" ]] || continue
    new="${f//class/classbak}"
    [[ "$f" != "$new" ]] && mv -- "$f" "$new"
done

進階工具推薦

  • rename (Perl 版):rename 's/class/classbak/' * 支援正則,功能強大。
  • mmv:mmv '*class*' '#1classbak#2' 適合複雜模式。
  • 圖介面:pyRenamer、GPRename。

掌握 Shell 參數展開,日常批量改檔名不再手忙腳亂。

Copyright © Windows教程網 All Rights Reserved