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

echo $srcText | sed "s/XPLACEHOLDERX/$connect"

The result is:

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

2 Answers 2


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//\//\\/}/"
  • +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

If your shell supports it:


You must log in to answer this question.

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