How can I fix this:
abc="a/b/c"; echo porc | sed -r "s/^/$abc/"
sed: -e expression #1, char 7: unknown option to `s'
The substitution of variable $abc
is done correctly, but the problem is that $abc
contains slashes, which confuse sed
. Can I somehow escape these slashes?
Note that sed(1)
allows you to use different characters for your s///
delimiters:
$ abc="a/b/c"
$ echo porc | sed -r "s|^|$abc|"
a/b/cporc
$
Of course, if you go this route, you need to make sure that the delimiters you choose aren't used elsewhere in your input.
The GNU manual for sed
states that "The / characters may be uniformly replaced by any other single character within any given s command."
Therefore, just use another character instead of /
, for example :
:
abc="a/b/c"; echo porc | sed -r "s:^:$abc:"
Do not use a character that can be found in your input. We can use :
above, since we know that the input (a/b/c/
) doesn't contain :
.
Be careful of character-escaping.
If using ""
, Bash will interpret some characters specially, e.g. `
(used for inline execution), !
(used for accessing Bash history), $
(used for accessing variables).
If using ''
, Bash will take all characters literally, even $
.
The two approaches can be combined, depending on whether you need escaping or not, e.g.:
abc="a/b/c"; echo porc | sed 's!^!'"$abc"'!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With