将Windows路径转换为Linux路径

时间:2013-08-06 13:38:23

标签: ruby path

目前我的路径为\\documents\videos\form.mov,但需要将路径更改为/documents/videos/form.mov。我尝试过使用路径分离器以及split。但它不允许分割路径,因为'\'是一个转义字符。

请允许任何人帮助我。

2 个答案:

答案 0 :(得分:3)

path = '\\\\documents\videos\form.mov'

new_path = path.gsub /\\+/, '/'

puts path, new_path

<强>输出

\\documents\videos\form.mov
/documents/videos/form.mov

以下是irb会话的副本

E:\Ruby\source>irb --simple-prompt
>> path = '\\\\documents\videos\form.mov'
=> "\\\\documents\\videos\\form.mov"
>> new_path = path.gsub /\\+/, '/'
=> "/documents/videos/form.mov"
>>

答案 1 :(得分:0)

现有的答案并没有达到我的期望,所以我不得不自己动手。这是模块及其单元测试。

module ConvertWindowsPath
  def convert_windows_path windows_path
    manipulated_windows_path = windows_path.clone
    unix_path = ""
    if windows_path.start_with? "\\\\" #it's on some network thing
      unix_path = "//"
      manipulated_windows_path = manipulated_windows_path[2..-1]
    elsif manipulated_windows_path.start_with? "\\"
      unix_path = "/"
    end
    unix_path += manipulated_windows_path.split("\\").join("/")
    unix_path += "/" if manipulated_windows_path.end_with?("\\")
    unix_path
  end
end

require 'test/unit'

class ConvertWindowsPathTest < Test::Unit::TestCase
  include ConvertWindowsPath
  def setup
    @expectations = {
      "C:\\" => "C:/",
      "\\\\vmware-host\\Shared Folders\\Foo\\bar-baz" => "//vmware-host/Shared Folders/Foo/bar-baz",
      "D:\\Users\\ruby\\Desktop\\foo.txt" => "D:/Users/ruby/Desktop/foo.txt",
      "z:\\foo\\bar\\" => "z:/foo/bar/"
    }
  end
  def test_expectations
    @expectations.each do |windows_path, expected_unix_path|
      assert_equal expected_unix_path, convert_windows_path(windows_path)
    end
  end
end