开发者

How to gsub slash "/" with back slash and slash "\/" in ruby

开发者 https://www.devze.com 2022-12-21 07:06 出处:网络
I try to modify \"/foo/bar/dir\" to \"\\/foo\\/bar\\/dir\" by ruby gsub command. I test it in irb the result is

I try to modify "/foo/bar/dir" to "\/foo\/bar\/dir" by ruby gsub command.

I test it in irb the result is

x = "/foo/bar/dir"

x.gsub("/","\/")

=> "/foo/bar/dir"

x开发者_开发知识库.gsub("/","\\/")

=> "\\/foo\\/bar\\/dir"

Is it possible to replace "/" with "/" by gsub ?


Source of problems:

I try to execute "string in command line" and "real_path" is my variable

real_path = "/home/me/www/idata"

path = real_path.gsub("/","\\/")

=> \\/home\\/me\\/www\\/idata 

# But what I expect is \/home\/me\/www\/idata

run "sed 's/SHARE_PATH/#{path}/g' #{path}/config/sphinx.yml > #{path}/config/sphinx.tmp.yml"

result from "run" command is

"sh -c 'sed '\''s/SHARE_PATH/\\/home\\/me\\/www\\/idata\\/shared/g .... "

I need is only one back slash like

"sh -c 'sed '\''s/SHARE_PATH/\/home\/me\/www\/idata\/shared/g .... "

"run" is command from Capistrano

my solution is

use single quote instead of double quote like this

path = real_path.gsub("/",'\/') 


You have written:

x = "/foo/bar/dir"
x.gsub("/","\\/")
=> "\\/foo\\/bar\\/dir"

so You did what You had asked before. x.gsub("/","\\/") in fact evaluates to "\/foo\/bar\/dir" but irb prints return value of inspect method instead of to_s.

Edit: Did You mean

real_path.gsub("/","\/")

istead of

real_path.gsub("\/","\/")

Anyway the output is correct - You changed / with \/ so You have

"sh -c 'sed '\''s/SHARE_PATH/\/home\/me\/www\/idata\/shared/g'\'' .... "`

instead of

`"sh -c 'sed '\''s/SHARE_PATH//home/me/www/idata/shared/g'\'' .... "`

and result is different from irb's result (notice the lack of doubled backslash).

For path manipulation I recommend using File.join (documentation)

By the way: why are You modifying the path this way? (1)

Edit2: Why are You asking about changing "/" to "/" but write the following line?

path = real_path.gsub("\/","\\/") 

What are You trying to achieve? And what is Your answer to question (1) ?

Edit3:

Here We go:

>> real_path = "/foo/bar/dir"
=> "/foo/bar/dir"
>> path = real_path.gsub("/", "\\/")
=> "\\/foo\\/bar\\/dir"
>> puts "sed 's/SHARE_PATH/#{path}/g' #{path}/config/sphinx.yml > #{path}/config/sphinx.tmp.yml"
sed 's/SHARE_PATH/\/foo\/bar\/dir/g' \/foo\/bar\/dir/config/sphinx.yml > \/foo\/bar\/dir/config/sphinx.tmp.yml
=> nil
>>

but I do not understand why You need backslash in a path?


Yes

irb(main):028:0> (t = x.gsub("/", "\\/")) && nil
=> nil
irb(main):029:0> t
=> "\\/foo\\/bar\\/dir"
irb(main):030:0> puts t
\/foo\/bar\/dir
=> nil

Your first example actually did what you wanted, but the .inspect method that irb is using is escaping backslashes, so it looked like there were extras. If you had used puts you would have seen the real result.

0

精彩评论

暂无评论...
验证码 换一张
取 消