16

I am looking for a way to replace a string in a file with a string that contains a slash by using sed.

connect="192.168.100.61/foo"
srcText="foo.bar=XPLACEHOLDERX"
echo $srcText | sed "s/XPLACEHOLDERX/$connect"

The result is:

sed: -e Expression #1, Character 32: Unknown option for `s'
1

2 Answers 2

34

Use another character as delimiter in the s command:

printf '%s\n' "$srcText" | sed "s|XPLACEHOLDERX|$connect|"

Or escape the slashes with ksh93's ${var//pattern/replacement} parameter expansion operator (now also supported by zsh, bash, mksh, yash and recent versions of busybox sh).

printf '%s\n' "$srcText" | sed "s/XPLACEHOLDERX/${connect//\//\\/}/"
3
  • +1 for second way. first one does not work on freebsd.
    – ibrahim
    Jul 8, 2014 at 11:11
  • I know it's not the question, but what if the string contains a backslash, perhaps followed by an 'n'....and you don't want it replaced by a single newline character? Jul 24, 2020 at 9:43
  • @MaxWaterman, if I understand you correctly, that backslash is in the $connect string, right? Then you have to escape it before reaching sed: printf '%s\n' "$srcText" | sed "s|XPLACEHOLDERX|${connect//\\/\\\\}|"
    – manatwork
    Jul 24, 2020 at 10:32
3

If your shell supports it:

"${srcText/XPLACEHOLDERX/$connect}"

You must log in to answer this question.

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