Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a path with another path in sed?

Tags:

path

sed

csh

I have a csh script (although I can change languages if it has any relevance) where I have to:

sed s/AAA/BBB/ file 

The problem is that AAA and BBB are paths, and so contain '/'. AAA is fixed, so I can say:

sed s/\\\/A\\\/A\\\A/BBB/ file 

However, BBB is based on variables, including $PWD. How do I escape the '/' in $PWD?

OR is there some other way I should be doing this entirely?

like image 955
Brian Postow Avatar asked Aug 21 '12 19:08

Brian Postow


People also ask

How do you use sed to replace multiple lines?

By using N and D commands, sed can apply regular expressions on multiple lines (that is, multiple lines are stored in the pattern space, and the regular expression works on it): $ cat two-cities-dup2.

What is S in sed command?

Substitution command In some versions of sed, the expression must be preceded by -e to indicate that an expression follows. The s stands for substitute, while the g stands for global, which means that all matching occurrences in the line would be replaced.


2 Answers

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.

like image 120
Lev Levitsky Avatar answered Oct 13 '22 17:10

Lev Levitsky


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

like image 34
c0m3t Avatar answered Oct 13 '22 15:10

c0m3t