Rename method of Ruby; escaping colon

那年仲夏 提交于 2019-12-25 08:05:09

问题


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).



来源:https://stackoverflow.com/questions/9559701/rename-method-of-ruby-escaping-colon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!