Ruby to rename files

2019-02-18 20:28发布

问题:

I have a script that renames files from a .csv file, this file works fine but am looking to edit it a little bit more so that it help me even more.

The scenario is I have 8,000 images that have a CID code some of them have the CID code some of them have extra text with it and are multiple images under the same CID ID i.e 17263.jpg 17263a.jpg, 17623b.jpg, I then need to rename the CID images with product codes to work on a website, as well as adding the relevant a or b or c letter after it, if there are multiple images I have the files CID files in the left hand of the .csv column but i don't have a easy way of matching the two code up together because there are so many.

I was wondering if there was a way of scripting ruby to search for the relevant cid code within the file name and rename it as the relevant product number?

Here is a link to where i downloaded the Script, i have changed it so it works with new ruby

http://roguepenguin.net/PFID2SKU/

Some of the file names are listed below just need the 5 digit code and a b or c etc if there are multiple images of this product

15144 a.jpg
15144 inset a.jpg
15144 inset b.jpg
15144 inset c.jpg
15144 inset d.jpg
15144 inset e.jpg
15144 inset f.jpg
15144 inset g.jpg
15144 inset h.jpg
15144 inset i.jpg
15155.jpg
15178.jpg
15233 a.jpg
15233 b.jpg
15233 box.jpg
15270.jpg
15321.jpg
15333 a.jpg
15333.jpg
15414 2010.jpg
15458 - 2632.jpg

Sorry for the mess up with the post earlier this week

Hope you can understand.

Thanks for the help.

回答1:

The Ruby file class has a rename() method. So you could search for the files you want to rename then use the File.rename() method to rename all of them.

Example:

product_name = "Some String";
id = 0;

filenames = Dir.glob("*.jpg")

filenames.each do |filename|
    File.rename(filename, product_name + id.to_s)
    id += 1
end


回答2:

Here's a little tidbit for you. Maybe it will help out. http://rtdptech.com/2010/08/ruby-shell-script-to-rename-files-in-a-folder/

I used something like this for a quickie because I wanted to use the rdoc/ri files to make little examples. I copied some directories to another location and the wanted to change the extension from *.ri to *.rb so I could put my runnable ruby code in.

here's the command line version

$ ruby -e "Dir.glob('*/*.ri').each {|i| File.rename(i, i.gsub('ri', 'rb'))}"

and here is file version

Dir.glob('*/*.ri').each {|i| File.rename(i, i.gsub('ri', 'rb'))}


标签: ruby rename