13

我正在尝试转义 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
4

2 回答 2

37

斯特凡是对的;我只想指出,如果您必须转义字符串以供 shell 使用,您应该检查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
于 2013-10-14T08:20:13.240 回答
12

那是字符串的inspect值,“str 的可打印版本,用引号括起来,特殊字符已转义”

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

只需打印字符串:

puts quoted

输出:

path/to/file\ with\ spaces
于 2013-10-14T08:14:05.733 回答