Use sed to replace each white space with a backslash
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.
12 Answers
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// /\\ } 3 [[:space:]] doesn’t match just spaces but rather all whitespace characters including tabs and line breaks. If you really want that, GNU sed (like in Ubuntu) has the shorthand class \s for it:
sed 's_\s_\\&_g'This substitutes every (g) whitespace character (\s, matches spaces, tabs and newlines embedded in the pattern/hold spaces) in every line with a backslash (\\) and itself – & is the whole matched pattern. I use a different delimiter because slashes and backslashes always look confusing together; s/\s/\\&/g is of course valid as well.
If you want to replace only space characters, rather use:
sed 's_ _\\&_g'Example run
$ echo "111 1111 " | sed 's_ _\\&_g'
111\ \ 1111\ For further reading on character classes see here on regular-expressions.info.
2