Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape file name for use in sed substitution

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?

like image 216
haelix Avatar asked Dec 04 '22 06:12

haelix


2 Answers

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.

like image 95
sarnold Avatar answered Dec 11 '22 16:12

sarnold


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:"
  1. 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 :.

  2. 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"'!'
      
like image 21
Rok Strniša Avatar answered Dec 11 '22 17:12

Rok Strniša