Вопрос по ruby – Как массово переименовать файлы в ruby
Я пытался разработать программу переименования файлов на основе ruby, как упражнение по программированию для себя (мне известно о переименовании под linux, но я хочу изучить Ruby, а переименование недоступно в Mac).
Из приведенного ниже кода проблема заключается в том, что.include?
Метод всегда возвращает false, хотя я вижу, что имя файла содержит такой шаблон поиска. Если я закомментируюinclude?
проверять,gsub()
похоже, не генерирует новое имя файла вообще (то есть имя файла остается неизменным). Так может кто-нибудь, пожалуйста, посмотрите, что я сделал не так? Большое спасибо заранее!
Вот ожидаемое поведение: Предполагая, что в текущей папке есть три файла: a1.jpg, a2.jpg и a3.jpg Скрипт Ruby должен иметь возможность переименовать его в b1.jpg, b2.jpg, b3.jpg
#!/Users/Antony/.rvm/rubies/ruby-1.9.3-p194/bin/ruby
puts "Enter the file search query"
searchPattern = gets
puts "Enter the target to replace"
target = gets
puts "Enter the new target name"
newTarget = gets
Dir.glob("./*").sort.each do |entry|
origin = File.basename(entry, File.extname(entry))
if origin.include?(searchPattern)
newEntry = origin.gsub(target, newTarget)
File.rename( origin, newEntry )
puts "Rename from " + origin + " to " + newEntry
end
end
rename
команда может добиться большего в этом ...
texasbruce
gets
подскажет?
bta
mv "old location" "new location"
не работает в терминале MacOS ??
Mr. Kennedy
puts "Enter the file search query"
searchPattern = gets.strip
puts "Enter the target to replace"
target = gets.strip
puts "Enter the new target name"
newTarget = gets.strip
Dir.glob(searchPattern).sort.each do |entry|
if File.basename(entry, File.extname(entry)).include?(target)
newEntry = entry.gsub(target, newTarget)
File.rename( entry, newEntry )
puts "Rename from " + entry + " to " + newEntry
end
end
Ключевые отличия:
Use.strip
to remove the trailing newline that you get from gets
. Otherwise, this newline character will mess up all of your match attempts.
Use the user-provided search pattern in the glob
call instead of globbing for everything and then manually filtering it later.
Use entry
(that is, the complete filename) in the calls to gsub
and rename
instead of origin
. origin
is really only useful for the .include?
test. Since it's a fragment of a filename, it can't be used with rename
. I removed the origin
variable entirely to avoid the temptation to misuse it.
Для вашего примера структуры папок введите*.jpg
, a
, а такжеb
для трех входных подсказок (соответственно) следует переименовать файлы так, как вы ожидаете.
которую я использовал сегодня (без сопоставления с образцом)
Сохраните его как файл rename.rb и запустите его в командной строке сruby rename.rb
count = 1
newname = "car"
Dir["/path/to/folder/*"].each do |old|
File.rename(old, newname + count.to_s)
count += 1
end
Я / Копия _MG_2435.JPG преобразована в car1, car2, ...
Ваша проблема в том, чтоgets
возвращает новую строку в конце строки. Так что, если вы наберете "foo" затемsearchPattern
становится"foo\n"
, Самое простое исправление:
searchPattern = gets.chomp
Я мог бы немного переписать ваш код:
$stdout.sync
print "Enter the file search query: "; search = gets.chomp
print "Enter the target to replace: "; target = gets.chomp
print " Enter the new target name: "; replace = gets.chomp
Dir['*'].each do |file|
# Skip directories
next unless File.file?(file)
old_name = File.basename(file,'.*')
if old_name.include?(search)
# Are you sure you want gsub here, and not sub?
# Don't use `old_name` here, it doesn't have the extension
new_name = File.basename(file).gsub(target,replace)
File.rename( file, new_path )
puts "Renamed #{file} to #{new_name}" if $DEBUG
end
end