使用Ruby gsub在Linux路径名中转义空格 [英] Escape spaces in a linux pathname with Ruby gsub

查看:130
本文介绍了使用Ruby gsub在Linux路径名中转义空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转义Linux路径中的空格.但是,每当我尝试转义反斜线时,我都会得到一个双斜线.

I am trying to escape the spaces in a Linux path. However, whenever I try to escape my backslash I end up with a double slash.

示例路径:

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

这样我就可以在Linux中使用它了,我想将其转义为:

So that I can use this in Linux I want to escape it as:

/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

推荐答案

Stefan是正确的;我只想指出,如果必须转义字符串以供Shell使用,则应检查

Stefan is right; I just want to point out that if you have to escape strings for shell use you should check 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

这篇关于使用Ruby gsub在Linux路径名中转义空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆