Ubuntu – Use sed to replace each white space with a backslash

command linesedtext processingwindows-subsystem-for-linux

Just want to escape spaces in windows filepath. I'm trying this:

echo "111  1111 "| sed -e "s/[[:space:]]/\\ /g"

that only match spaces but do not replace.

Best Answer

If you use double quotes, bash interprets \\ and outputs \ which is then again interpreted from sed together with the following space to just the space.

So you need one more backslash:

echo "111  1111 " | sed -e "s/[[:space:]]/\\\ /g"

but better to use single quotes to prevent the bash interpreting:

echo "111  1111 " | sed -e 's/[[:space:]]/\\ /g'

Output:

111\ \ 1111\ 

Alternative method:

If you have the file path as a variable, you can use Shell methods:

path="111  1111 "
echo ${path// /\\ }