1

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.

  • I agree, the title is misleading ;-) But "ecran[sic] spaces in ... filepath" is pretty clear. echo "111 1111 " has a fixed number of whitespace, so I don't really get your quesiton. – pLumo Dec 14 '18 at 14:53
4

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// /\\ }
| improve this answer | |
  • What would the out put be like? – George Udosen Dec 14 '18 at 14:47
  • 1
    +1 for Alternative method. – WinEunuuchs2Unix Dec 14 '18 at 23:57
  • nice method with variable, thanks. It is useful for my .bashrc – Yurij Dec 15 '18 at 14:53
1

[[: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.

| improve this answer | |
  • Thanks, it works too. an unusual form of regex. not so widely common? – Yurij Dec 15 '18 at 15:01
  • @Yurij I didn’t use any regex, do you mean & for the entire matched pattern? That’s actually quite common… – dessert Dec 15 '18 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.