Escape spaces in a linux pathname with Ruby gsub

亡梦爱人 提交于 2019-12-05 00:10:30

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

That is the string's inspect value, "a printable version of str, surrounded by quote marks, with special characters escaped":

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

Just print the string:

puts quoted

Output:

path/to/file\ with\ spaces
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!