Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux rename 命令:批量重命名文件的神器,告別手寫腳本

編輯:Linux 教學

mv 只能單個重命名,批量改名常寫 for 循環。其實 rename (Perl 版) 一條命令搞定 90% 場景,支持正則替換、序號補零、擴展名統一。

一、 命令語法

rename [選項] 's/舊模式/新模式/' 文件列表
# 或傳統語法
rename 字符串1 字符串2 文件列表

二、 核心參數

參數說明
-v, --verbose顯示重命名詳情
-n, --no-act試運行,不實際修改
-f, --force強制覆蓋同名文件
-e, --exprPerl 表達式 (可多次使用)

三、 經典場景實戰

1. 統一前綴:hs_ok_all_* → hs_*

rename 's/^hs_ok_all_/hs_/' hs_ok_all_*
# 結果:hs_ok_all_200911.txt → hs_200911.txt

2. 擴展名批量修正:.htm → .html

rename 's/\.htm$/.html/' *.htm

3. 序號補零:foo1..foo9 → foo01..foo09

rename 's/^foo(\d)$/foo0$1/' foo?
# 或
rename 's/^foo(\d+)$/sprintf("foo%03d",$1)/e' foo*

4. 大小寫轉換

# 全小寫
rename 'y/A-Z/a-z/' *

# 全大寫
rename 'y/a-z/A-Z/' *

5. 刪除特定字符

rename 's/_bak//' *_bak.txt

6. 遞歸處理子目錄


find . -name "*.log" -exec rename 's/\.log$/.txt/' {} \;

四、 兩個版本區別

版本來源語法功能
Perl 版 (prename)util-linux / Perlrename 's///' file正則表達式,功能強大
C 版 (rename.ul)util-linuxrename str1 str2 file簡單字符串替換

檢查版本:rename --version。大多數現代發行版默認 Perl 版。

五、 避坑指南

  • 先加 -n 試運行,確認無誤再執行。
  • 通配符由 Shell 展開,參數過長報錯時用 find -exec 或 xargs。
  • 正則中特殊字符需轉義:. * ? [ ] ( ) { } ^ $ | \。
  • 文件名含空格時用引號包裹或 find -print0 | xargs -0。

六、 一鍵速查卡


# 1. 替換字符串
rename 's/old/new/' *

# 2. 修改擴展名
rename 's/\.jpg$/.png/' *.jpg

# 3. 添加前綴
rename 's/^/prefix_/' *

# 4. 添加後綴
rename 's/$/_suffix/' *

# 5. 刪除前 4 字符
rename 's/^.{4}//' *

# 6. 試運行
rename -n 's/foo/bar/' *
Copyright © Windows教程網 All Rights Reserved