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
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
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
brew install gnu-sed
and use gsed
instead of sed
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'
Have you try to use something like:
sed -i 's@/var/www@/home/lokesh/www@g' lks.php
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)