35

I want to change in file /var/www with /home/lokesh/www with sed command

sed -i 's///var//www///home//lokesh//www/g' lks.php

but this give error

sed: couldn't open file ww///home//lokesh//www/g: No such file or directory

4 Answers 4

80

Not sure if you know, but sed has a great feature where you do not need to use a / as the separator.

So, your example could be written as:

sed -i 's#/var/www#/home/lokesh/www#g' lks.php

It does not need to be a # either, it could be any single character. For example, using a 3 as the separator:

echo "foo" | sed 's3foo3bar3g'
bar
3
  • if you're using sed to insert lines after or before a match, you don't use s/ but just / and with this you can use / in your replacement string. sed -i '/^.*my.match.pattern.*$/i \ <logger name="my.replacement.pattern" level="DEBUG"/>' logback.xml
    – dr jerry
    Sep 2, 2021 at 12:39
  • If you're on a Mac, brew install gnu-sed and use gsed instead of sed
    – Ahi Tuna
    Jan 7, 2023 at 22:49
  • 1
    Lovely. Helped a lot
    – saumilsdk
    Feb 9, 2023 at 7:08
13

You can use a different character for the delimiter, as others have pointed out, like this:

sed -i 's!pattern!replacement!g' /path/to/file

But if there is no convenient character to use instead of / as the delimiter, you can also escape any embedded delimiter characters in your pattern and replacement by prefixing them each with a backslash \. Here's an example using / as the delimiter that replaces /some/path with ../some/replacement:

sed -i 's/\/some\/path/..\/some\/replacement/g'

It's harder for humans to read, though, so generally if it's at all possible it's better to use a different character for the delimiter like this:

sed -i 's!/some/path!../some/replacement!g'
4

Have you try to use something like:

sed -i 's@/var/www@/home/lokesh/www@g' lks.php
3

You can put a simple premat command in front of the sed command in the bash script, which masks the slash in path variables. Let's assume the path variable to be swapped is in $P0:

P0="/foo/foo/foo/file"; 
P0=(${P0////\\/});  #masked Slash to form: \/foo\/foo\/foo\/file

Should be exchanged with:

P1="/whatever/youwant/file"; 
P1=(${P1////\\/}); #masked slash to form \/whatever\/youwant\/file

With sed simply afterwards:

sed -i "s/${P0}/${P1}/" /wherever/that/should/go/file;

This works in bash --version 5.1.4(1)

1
  • IMHO best way to go with random output strings, except if they contain spaces. Dec 2, 2023 at 20:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .