2013-10-14 33 views
10

我試圖在Linux路徑中轉義空格。然而,每當我試圖逃避我的反斜槓,我最終都會出現雙斜槓。使用Ruby轉義Linux路徑名中的空格gsub

示例路徑:

/mnt/drive/site/usa/1201 East/1201 East Invoice.pdf 

所以,我可以在Linux上使用這個我想逃避它:

/mnt/drive/site/usa/1201\ East/1201\ East\ Invoice.pdf 

所以我想這樣的:

backup_item.gsub("\s", "\\\s") 

但我得到一個意想不到的輸出

/mnt/drive/site/usa/1201\\ East/1201\\ East\\ Invoice.pdf 

回答

29

Stefan is對;我只是想指出的是,如果你有逃避外殼字符串使用,你應該檢查Shellwords::shellescape

require 'shellwords' 

puts Shellwords.shellescape "/mnt/drive/site/usa/1201 East/1201 East Invoice.pdf" 
# prints /mnt/drive/site/usa/1201\ East/1201\ East\ Invoice.pdf 

# or just 

puts "/mnt/drive/site/usa/1201 East/1201 East Invoice.pdf".shellescape 
# prints /mnt/drive/site/usa/1201\ East/1201\ East\ Invoice.pdf 
+1

或'shellwords.escape('/ mnt/drive/site/usa/1201 East ...')'。 – hagello

8

這是字符串的inspect值,「海峽的打印版本,用引號包圍,有特殊字符轉義」

quoted = "path/to/file with spaces".gsub(/ /, '\ ') 
=> "path/to/file\\ with\\ spaces" 

只打印字符串:

puts quoted 

輸出:

path/to/file\ with\ spaces 
+0

只爲任何人考慮使用此解決方案:Shellwords也轉義特殊字符,如'$ {} []'等 – Wukerplank