Rename method of Ruby; escaping colon

2019-08-17 04:13发布

问题:

How do you escape a colon, when renaming files in Ruby?

I have following code (names is a hash with data already filled in):

new_filename = ""
counter = 0 
Dir.glob(folder_path + "/*").each do |f|
  numbering = names.index(names.values.sort[counter])
  new_filename = numbering + " - " + names.values.sort[counter]
  puts "New file name: " + new_filename
  File.rename(f, folder_path + "/" + new_filename + File.extname(f))
  counter += 1
end

puts "Renaming complete."

The output of new_filename is correct, e.g. "Foo - Bar: Foo.txt". When it renames the file, the file has following format: "Foo - Bar/ Foo.txt".

I tried escaping with the colon with a backslash, but doesn't seem to work, because my output then looks like this: "Foo - Bar/\ Foo.txt".

Is is possible to have a colon in a string for renaming files?

回答1:

FYI - in NTFS a colon identifies a separate stream of the same file... "Foo Bar: Foo.txt" identifies file "Foo Bar", stream " Foo.txt". Reference "Alternate Data Streams" (currently http://support.microsoft.com/kb/105763). AFIK this feature is not really widely used, though I have seen it used to tag files with thrid-party data (I use it to store a file's sha1 for dupe identification under the stream *:sha1).