12

E.g.,

sed 's/string/ /g' where string="a\c:ti]\']x""/\//:`~$%#^&"'

That is how to pass the string to sed literally rather than as an interpreted regex pattern?

I'm going to use this with cygwin and on ubuntu, so the solutions should be compatible with the environment.

1

2 Answers 2

5

You should escape the special characters and use a separator other than "/".

sed 's#string1#string2#'
2
  • I most often see | when using sed.
    – Rob
    Apr 7, 2012 at 0:33
  • Admittedly, this is one ugly string. Apr 7, 2012 at 0:35
1

See this SOq:

This answer on the above:

is something you need, except you'd do it in the first, not second part of s/first/second/.

As you are using both ' and " in your sed commands, you'll have to escape some of it. Try doing this - make two files:

1.sed

s_"a\\c:ti]\\']x""/\\//:`~\$%#\^&"'_ _g

2.txt

"a\c:ti]\']x""/\//:`~$%#^&"'hello world m"a\c:ti]\']x""/\//:`~$%#^&"'
"a\c:ti]\']x""/\//:`~$%#^&"'this is working"a\c:ti]\']x""/\//:`~$%#^&"'
"a\c:ti]\']x""/\//:`~$%#^&"'as expected"a\c:ti]\']x""/\//:`~$%#^&"'

1.sed is the script itself and 2.txt is a test file. Run it like this to test:

$ sed -f 1.sed 2.txt
 hello world m 
 this is working 
 as expected 

$ 

Hope this helps.

4
  • What command to use for escaping? echo "a\c:ti]\']x""/\//:`~$%#^&"'|sed -e 's/([[\/.*]\|])/\\&/g' results in a > prompt in bash.
    – user93200
    Apr 7, 2012 at 2:30
  • If you mix both ' (single quote) and " (double quote), you will have to escape something in the string. This is not a "problem" with sed per-se, even if you do just echo "a\c:ti]\']x""/\//:~$%#^&"', it will be not a complete string. E.g. you cannot do echo "abc"" and expect it to print abc"` - you have to escape the ". Apr 7, 2012 at 2:32
  • Could you provide a command to automatically escape any given string and also elaborate on how the solution might be affected by the environment (running in bash or in cmd.exe)?
    – user93200
    Apr 8, 2012 at 2:42
  • The command in the provided links gives you that (the one you put in your first comment to my answer). The problem is that you cannot do that the way you want - the input from echo command cannot even get to the sed to be escaped, it has to be escaped in-place to be even printed by echo correctly. The other solution - putting the string into the file - is what would work, see my edit. Hope that will work for you. Apr 8, 2012 at 14:29

You must log in to answer this question.

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