Bash sed problem

Hi,

I need to escape slashes in my text, so I use this line:

search_string=`echo $var | sed 's@/@\\\/@g'`

I expect that to replace a slash with a backslash followed by a slash. That works nicely, but it has a problematic side-effect. If there are two spaces in the var it replaces them with one space. For example:

var="test1/test2<space><space>test3"
search_string=`echo $var | sed 's@/@\\\/@g'`
echo "$search_string"

produces test1\/test2<space>test3

What happened to the other space between test2 and test3?

(by <space> I mean one space character)

search_string=`echo "$var" | sed 's@/@\\\/@g'`
1 Like

Thanks. What's the deal? It doesn't preserve spaces unless you surround it with quotes?

that is correct - whitespace is removed by the shell.

I suggest removing it via the built-in functionality rather then use sed.

ie:

search_string=${var//\//\\/}
1 Like