I need to replace Unix path via sed with variable that contain another unix path in a bash script
Example:
another_unix_path=/another/unix/path
sed -i 's/ \/some\/path\/file.txt/ '$another_unix_path'/g' some_file.txt
I need to replace Unix path via sed with variable that contain another unix path in a bash script
Example:
another_unix_path=/another/unix/path
sed -i 's/ \/some\/path\/file.txt/ '$another_unix_path'/g' some_file.txt
Escaping special char /
is an option.
You can also change the default sed
separator (which is /
) by using ?
for example :
another_unix_path="/another/unix/path"
echo /some/path/file.txt | sed -e 's?/some/path/file.txt?'$another_unix_path'?g'
The char used just after the s
flag defines which separator will be used : s?
Edit :
#!/bin/sh
basepath=/another/unix/path
baseurl=/base/url
sed -i 's?# set $IMAGE_ROOT /var/www/magento2;? set $IMAGE_ROOT '$basepath$baseurl';?g' somefile.txt
If you use /
for separators, then you'll have to escape every /
in your path, ex sed 's/\/some\/path/'$replacement'/g'
Fortunately sed - like Perl - allows many characters to be used as separators, so you can also write sed 's#/some/path#'$replacement'#g'
(the g
flag is used to allow replacing multiple occurrences per line).
Also sed will not allow in-place replacement if you run it on a file, meaning you will have to write to a temp file and move it over. Update: actually, Gnu's sed does have an in-place option which work like Perl's: -i
or -i.ext
where .ext
is the backup extension. Perl may be preferable for portability though.
For in-place replacement you can use Perl as such:
# In-place without backup:
perl -pi -e 's#/some/path#'$replacement'#g' <file>
# In-place with backup as .orig (note .orig is glued to the -i switch):
perl -pi.orig -e 's#/some/path#'$replacement'#g' <file>
Be careful with the 2nd command, as if you enter it twice you will overwrite your first backup!
You need to escape special characters:
another_unix_path="\/another\/unix\/path"
echo /some/path/file.txt | sed -e 's/\/some\/path\/file.txt/'$another_unix_path'/g'
Which outputs this result:
/another/unix/path