LoginSignup
85
79

More than 5 years have passed since last update.

Linuxでrenameコマンドを使おう

Posted at

ファイル名をリネームするのにはmvでできますが、カレントディレクトリから深いところにあるファイルとかをリネームするとき

mv ./hara/horo/hire/hare/foo.txt ./hara/horo/hire/hare/bar.txt

とかちょっとアレです
そんなときはrenameコマンド
https://wiki.ubuntulinux.jp/UbuntuTips/FileHandling/RenameCommand
UNIXにこのコマンドがないこともあって余り知られていませんが、どのLinuxにも含まれています。・・・とのことです。

rename s/foo/bar/ ./hara/horo/hire/hare/foo.txt

でリネームできます.
なんかmanに書いてあるとおりでは動かなくて、rename perl正規表現 対象ファイルで動きます

このコマンド、perlのスクリプトなんで開いてみると

whereis rename
die "Usage: rename [-v] [-n] [-f] perlexpr [filenames]\n"
    unless GetOptions(
  'v|verbose' => \$verbose,
  'n|no-act'  => \$no_act,
  'f|force'   => \$force,
    ) and $op = shift;

-vオプションが指定できます

じぶんは.bash_profileや.bashrcに書いておきました

alias 'rename'='rename -v'
$ rename s/foo/bar/ foo.txt 
foo.txt renamed as bar.txt

と出力結果を教えてくれます
もちろん本領は正規表現で指定できることでソースのサンプルなんかが参考になります

例えば、.bakという拡張子を全部とるとか
For example, to rename all files matching C<*.bak> to strip the extension,
you might say

  rename 's/\.bak$//' *.bak

大文字を小文字に変えるとか
To translate uppercase names to lower, you'd use

  rename 'y/A-Z/a-z/' *
85
79
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
85
79