Skip to content

Instantly share code, notes, and snippets.

@tomoyamkung
Created September 24, 2012 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomoyamkung/3773889 to your computer and use it in GitHub Desktop.
Save tomoyamkung/3773889 to your computer and use it in GitHub Desktop.
[Ruby]リネームスクリプト
#! ruby
#-*- encoding: utf-8 -*-
require 'getoptlong'
#search_pattern = '-DVD-BOX-'
#replace_pattern = 'DVD-BOX '
opts = GetoptLong.new(
['--confirm', '-c', GetoptLong::NO_ARGUMENT],
['--search', '-s', GetoptLong::REQUIRED_ARGUMENT],
['--replace', '-r', GetoptLong::REQUIRED_ARGUMENT]
)
confirm = false
search_pattern = ''
replace_pattern = ''
begin
opts.each do |opt, arg|
case opt
when "--confirm"
confirm = true
when "--search"
search_pattern = arg
when "--replace"
replace_pattern = arg
end
end
rescue => ex
STDERR.puts("Usage:...") # TODO
exit 1
end
Dir::glob('*' + search_pattern + '*').each do |file|
after = file.sub(search_pattern, replace_pattern)
if confirm
puts after
else
File::rename(file, after)
end
end
# ■これはなに
#  カレントディレクトリにあるファイル名を置換する
# ■オプション
#  -c:リネームを実行せずに、リネーム後のファイル名を表示する
#  -s(必須):リネームしたいファイル名を検索するキーワード。ここで指定した文字列を置換する
#  -r(必須):置換する文字列を指定する
# ■実行例
#  ▼リネーム後のファイル名確認する
#   $ ruby rename.rb -c -s 'あの' -r 'この'
#  ▼リネームする
#   $ ruby rename.rb -s 'あの' -r 'この'
#   => 'あの'を含むファイル名を'この'にリネームする(「あのファイル.txt」 → 「このファイル.txt」)
# ■備考
#  - 空白文字も指定したい場合は文字列を '(シングルクォート)で囲むこと
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment