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'
peterh
  • 9,731
martin
  • 439

2 Answers2

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//\//\\/}/"
manatwork
  • 31,277
  • +1 for second way. first one does not work on freebsd. – ibrahim Jul 08 '14 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? – Max Waterman Jul 24 '20 at 09: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 '20 at 10:32
3

If your shell supports it:

"${srcText/XPLACEHOLDERX/$connect}"