我试图逃避Linux路径中的空格。但是,每当我试图逃避反斜杠时,我都会以双斜线结束。
示例路径:
/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
答案 0 :(得分:33)
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
puts "/mnt/drive/site/usa/1201 East/1201 East Invoice.pdf".shellescape
# prints /mnt/drive/site/usa/1201\ East/1201\ East\ Invoice.pdf
# or (as reported by @hagello)
puts shellwords.escape "/mnt/drive/site/usa/1201 East/1201 East Invoice.pdf"
# prints /mnt/drive/site/usa/1201\ East/1201\ East\ Invoice.pdf
答案 1 :(得分:9)
这是字符串的inspect
值,“str的可打印版本,由引号括起,特殊字符已转义”:
quoted = "path/to/file with spaces".gsub(/ /, '\ ')
=> "path/to/file\\ with\\ spaces"
只需打印字符串:
puts quoted
输出:
path/to/file\ with\ spaces