how to replace “/” on path string with “\\/” using sed?

扶醉桌前 提交于 2019-12-01 18:37:01

Add a g flag to your substitute command:

echo "${PATH}" | sed 's/\//\\//g'

Or more readable, as per Jonathan Wakely in the comments:

echo "${PATH}" | sed 's:/:\\/:g'

To achieve what you describe in your question, you need one more backslash:

echo /user/dj/a/mydir | sed 's:/:\\\/:g'

Output:

\/user\/dj\/a\/mydir

Use Shell's parameter expansion, if you are running a shell script:

MYPATH="/user/dj/a/mydir"
PATH_FORMAT=${MYPATH////\\/}

The substition ${parameter} is extended by the syntax ${parameter//pattern/string} which replaces all patterns found in parameter. The pattern can be a regular expression. In your case the pattern is: /. The replace string is: \\/.

Furthermore, avoid storing something in the variable PATH, because it is probably used by the system -- unless you want to modify the systems path variable.

Quoting gnu.org's manual on parameter expension:

${parameter/pattern/string}

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. The match is performed according to the rules described below (see Pattern Matching). If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If the nocasematch shell option (see the description of shopt in The Shopt Builtin) is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

looper
sed "s%/%\\\\\\/%g"

. As Simple as that

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