【问题标题】:Reducing filenames in a directory and renaming them in Ruby减少目录中的文件名并在 Ruby 中重命名它们
【发布时间】:2022-11-18 03:42:04
【问题描述】:

极端新手在这里!我有多个图像 (jpg),它们的文件名很长。我想将文件名减少到前六位数字。所以我认为他们需要进入一个数组以启用计数。复杂的是,每个产品可能有不止一张图片,所以我需要计算并添加 ~1、~2 等。

示例: 原始文件名:

110312_Classic Color彩色铅笔纸板钱包16件_Office_67779.jpg 110312_Classic Color彩色铅笔纸板钱包16件_Office_52779.jpg

我如何需要它们: 110312~1.jpg 110312~2.jpg

谢谢!

老实说,我才刚刚开始我的 Ruby 课程,所以还没有设法将任何代码放在一起。

【问题讨论】:

  • 110312~2.jpg 这看起来像是 30 年前的 MSDOS。

标签: ruby


【解决方案1】:

你可以这样做:

Dir.glob("<your global path to the image directory>/**/*.jpg").each_with_object(Hash.new(0)) do |file_path, acc|
  # get filename without global path
  filename = File.basename(file_path, '.jpg')
  # match first 6 characters
  new_filename = filename[0...6]
  # counter how many duplicates for index names
  # NOTE. Passed Hash.new(0) as the #each_of_object argument always returns 0 for a non-existent key.
  # Ex:
  # hash = Hash.new(5) => {}
  # hash['foo'] = 'bar' => 'bar'
  # hash['non_existed_key'] => 5
  # hash['foo'] => 'bar'
  acc[new_filename] += 1
  # collect full name with global file path
  new_filepath = "#{File.dirname(file_path)}/#{new_filename}~#{acc[new_filename]}.jpg"
  # rename the file
  File.rename(file_path, new_filepath)
end

Dir.glob('.../**/') 也匹配嵌套目录。如果你不需要它们,你就做 Dir.glob('.../')

【讨论】:

    猜你喜欢
    • 2015-07-09
    • 2022-01-06
    • 1970-01-01
    • 2013-12-23
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    相关资源
    最近更新 更多