0

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
2
  • What work have you done on this so far? Please provide examples you've tried, and how they didn't end up working for you.
    – EEAA
    May 20, 2015 at 11:55
  • 1
    Duplicate of Stack Overflow question.
    – l0b0
    May 20, 2015 at 12:00

3 Answers 3

-1

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

0
3

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
1
  • @user289782 See my edit
    – krisFR
    May 20, 2015 at 12:51
1

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!

0

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