LoginSignup
28
29

More than 5 years have passed since last update.

ファイル名を一括置換するRubyスクリプト

Posted at

やりたいこと

カレントディレクトリにあるファイル名を置換します。

方法

ファイル名をDir.globで得て、String#gsubで置き換えて、FileUtils.mvで変更します。

以下では、カレントディレクトリにある1.html, 2.html, ... 10.html, ... 100.htmlのようなファイル名を、頭に0を付けて001.html, 002.html, ... 010.html, ..., 100.htmlに置換しています。

rename.rb
require 'fileutils'

Dir.glob("*.html") do |filename|
  newname = filename.gsub(/^(\d+)/, sprintf("%03d", $1.to_i))
  FileUtils.mv(filename, newname)
end
28
29
1

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
28
29