我试图在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

最佳答案

斯蒂芬是对的。我只想指出,如果您必须转义字符串以供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

10-07 23:13