Escape spaces in a linux pathname with Ruby gsub

user1074981 picture user1074981 · Oct 14, 2013 · Viewed 9.6k times · Source

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.

Example path:

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

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

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

So I'm trying this:

backup_item.gsub("\s", "\\\s")

But I get an unexpected output of

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

Answer

mdesantis picture mdesantis · Oct 14, 2013

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