简体   繁体   中英

How to loop through folders and rename files

I am looping in folder like this

Dir.glob('**/*.tif').each do |image_file|

I get images/SW/SW-9.tif , i want to change to images/SW/SW-9.png and not duplicate, the .tif file should be deleted.

I want to rename all that files from .tif to .png

Dir.glob returns the full path.

Step 1: gsub .tif to .png

Step 2: Check the new name isn't a duplicate

Step 3: Use mv


Dir.glob('./**/*.tif').each do |path|
  dest_path = path.gsub(".tif", ".png")
  unless File.exists?(dest_path)
    `mv "#{path}" "#{dest_path}"`
  end
end

edited with suggestion from comment

Dir.glob('./**/*.tif').each do |path|
  dest_path = path.gsub(/\.tif\z/, '.png')
  unless File.exists?(dest_path)
    File.rename(path, dest_path)
  end
end

应该这样做:

Dir.glob('./**/*.tif').each { |img| File.rename(img, img.gsub(/tif$/, 'png')) unless File.exists?(img.gsub(/tif$/, 'png')) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM