Skip to content

[Linux] 使用 rename 指令透過正規表示式(Regular Expression)訂定格式替大量檔案改名

在 Linux 中,若是我們需要替大量的文件檔案批次進行改名,除了撰寫腳本使用 mv 指令外,也可以透過 rename 指令設立規則(就像正規表示式 Regular Expression 一般),替大量的檔案進行改名。

不過,在不同的系統上,有時內建的 rename 的使用方法不盡相同。除了參考下方的紀錄外,也需要自己進行測試。


下載 rename

Ubuntu

apt install rename


CentOS(prename: perl-rename)

yum install prename


MacOS

brew install rename

rename 指令的使用方法

基本使用方法

rename "s/STRING/NEW_STRING/" FILEs


在正式替文件改名前,可以加上 -n 參數檢視改名後的結果。假設我當前目錄底下有著 F1、F2、F3 等三份檔案,那我使用以下指令:

rename -n "s/F/X/" *


Output:

'F1' would be renamed to 'X1'
'F2' would be renamed to 'X2'
'F3' would be renamed to 'X3'


可以看到改名後的結果、並不會真正更動到檔案名稱。(註:* 表示當前路徑底下的所有檔案



在檔案開頭插入文字(使用 ^ 符號)

rename "s/^/A/" *


Output:

AF1  AF2  AF3




在檔案結尾插入文字(使用 $ 符號)

rename "s/$/_/" *


Output:

AF1_  AF2_  AF3_



刪除檔案名稱中的文字

rename "s/A//" *
rename "s/_//" *


Output

F1  F2  F3

References


Read More

Tags:

Leave a Reply