Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape spaces in a linux pathname with Ruby gsub

Tags:

ruby

gsub

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
like image 889
user1074981 Avatar asked Oct 14 '13 07:10

user1074981


1 Answers

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
like image 123
Stefan Avatar answered Sep 19 '22 14:09

Stefan