Escape file name to use in sed replacement

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 $abc variable is substituted correctly, but the problem is that $abc contains slashes that confuse sed . Is there any way to avoid these slashes?

+4
source share
5 answers

The GNU guide for sed states that "the / characters can be uniformly replaced with any other single character in any given s command."

So just use a different character instead of / , for example::

 abc="a/b/c"; echo porc | sed -r "s:^:$abc:" 
  • Do not use the character that can be found at your input. We can use : above, since we know that the input ( a/b/c/ ) does not contain :

  • Be careful with escaping characters.

    • If you use "" , Bash will interpret some characters specifically, for example. ` (used for inline execution) ! (used to access Bash history ), $ (used to access variables).

    • If used, '' Bash will accept all characters literally, even $ .

    • The two approaches can be combined depending on whether you need to screen or not, for example:

       abc="a/b/c"; echo porc | sed 's!^!'"$abc"'!' 
+6
source

Note that sed(1) allows the use of different characters for s/// delimiters:

 $ abc="a/b/c" $ echo porc | sed -r "s|^|$abc|" a/b/cporc $ 

Of course, if you are following this route, you need to make sure that the selected delimiters are not used elsewhere in your input.

+7
source

You do not need to use / as a template and replace the delimiter, as others have told you. I would go with : since it is rarely used in paths (this is a delimiter in the PATH environment variable). Stick to one and use the built-in string replacement functions to make it bulletproof, for example. ${abc//:/\\:} (which means replacing all : occurrences with \: in ${abc} ) if : is a delimiter.

 $ abc="a/b/c"; echo porc | sed -r "s:^:${abc//:/\\:}:" a/b/cporc 
+3
source

backslash:

 abc='a\/b\/c' 

filling the space ....

+1
source

As for the elusive part of the question, I had the same problem and resolved with a double sed that can be optimized.

 escaped_abc=$(echo $abc | sed "s/\//\\\AAA\//g" | sed "s/AAA//g") 

The triple A is used, because otherwise the forward slash after its backslash character never fits in the output, no matter how many backslashes you put in front of it.

0
source

Source: https://habr.com/ru/post/1385444/


All Articles