ターミナルからファイルのリネームを実行するrenameの使い方

ターミナルでの複数リネームは複雑

ターミナルでコマンドを実行して複数のファイルを実行しようとするとコマンドが長くなってしまう。

find src -name "*.foo" | sed -e 's/\.foox$/.bar/' | xargs -I{} mv {}foo {}

brew install renameでリネームを簡単に

brew install renameでrenameをインストールするとファイルのリネームが簡単にできるようになる。

brew install rename

renameの使い方は以下の通り。

renameコマンド一覧

fooをbarにリネームする

rename -s 'foo' 'bar' *
■ 実行前
foo.html
foo.js
dir/foo.html

■ 実行後
bar.html
bar.js
dir/foo.html

fooをbarにリネームする(ディレクトリ再帰)

rename -s 'foo' 'bar' **/*
■ 実行前
foo.html
foo.js
dir/foo.html

■ 実行後
bar.html
bar.js
dir/bar.html

.htmlのfooをbarにリネームする

rename -s 'foo' 'bar' **/*.html
■ 実行前
foo.html
foo.js
dir/foo.html

■ 実行後
bar.html
foo.js
dir/bar.html

正規表現でリネームする

rename 's/foo(\d\.html)$/bar$1/' *
■ 実行前
foo.html
foo1.html
foo2.html
foo.js
dir/foo.html

■ 実行後
foo.html
bar1.html
bar2.html
foo.js
dir/foo.html

-nで置換されるファイルを確認する

実行後にどのファイルが置換されるか事前に確認するには-nを付ける。

■ ファイル一覧
foo.html
foo1.html
foo2.html
foo.js
dir/foo.html
$ rename -n 's/foo(\d\.html)$/bar$1/' *
'foo1.html' would be renamed to 'bar1.html'
'foo2.html' would be renamed to 'bar2.html'

拡張子のみ置換する

例えば.htmを.htmlにするには以下の通り。

rename -s .htm .html *.htm
■ 実行前
foo.html
bar.htm

■ 実行後
foo.html
bar.html

-xで拡張子を除外する

rename -x *.html
■ 実行前
foo1.html
foo2.html

■ 実行後
foo1
foo2

-iでy/nで置換するものを選択

-iでy/nで置換するものを選択できる。

$ rename -i 's/foo(\d\.html)$/bar$1/' *
Rename 'foo1.html' to 'bar1.html' (y/n)? [n] n
Rename 'foo2.html' to 'bar2.html' (y/n)? [n] y
■ 実行前
foo1.html
foo2.html

■ 実行後
foo1.html
bar2.html