How to replace a path with another path in sed?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 14:16:50
Lev Levitsky

sed can use any separator instead of / in the s command. Just use something that is not encountered in your paths:

s+AAA+BBB+

and so on.

Alternatively (and if you don't want to guess), you can pre-process your path with sed to escape the slashes:

pwdesc=$(echo $PWD | sed 's_/_\\/_g')

and then do what you need with $pwdesc.

In circumstances where the replacement string or pattern string contain slashes, you can make use of the fact that GNU sed allows an alternative delimiter for the substitute command. Common choices for the delimiter are the pipe character | or the hash # - the best choice of delimiting character will often depend on the type of file being processed. In your case you can try

sed -i 's#/path/to/AAA#/path/to/BBB#g' your_file

Note: The g after last # is to change all occurrences in file if you want to change first ouccurence do not use g

Using csh for serious scripting is usually not recommended. However, that is tangential to the issue at hand.

You're probably after something like:

sed -e "s=$oldpath=$newpath="

where the shell variable $oldpath contains the value to be replaced and $newpath contains the replacement, and it is assumed that neither variable contains an equals sign. That is, you're allowed to choose the delimiter on pattern, and avoiding the usual / delimiter avoids problems with slashes in pathnames. If you think = might appear in your file names, choose something less likely to appear, such as control-A or control-G.

sed -i "s|$fileWithPath|HAHA|g" file

You can use parenthesis expansion ${i/p/r} to escape the slashes. In this case ${i//p/r} for escaping all occurrences.

$p1=${p1//\//\\/}
$p2=${p2//\//\\/}
sed s/$p1/$p2/ file

Or, more concise, in one line sed s/${p1//\//\\/}/${p2//\//\\/}/ file

The two fist slashes // are a separator in parenthesis expansion saying we are matching all occurrences, then \/ is for escaping the slash in the search template, the / as a second separator in the expansion, and then \\/ is the replacement, in witch the backslash must be escaped.

We just needed to get the /h/ network path references out of the path. if we pointed them back to the /c/ drive they would map to non-existant directories but resolve quickly. In my .bashrc I used

PATH=`echo $PATH | sed -e "s+/h/+/c/+g"`
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!