4

I'm trying to pass a variable with spaces in it to sed using BASH, and in the prompt, it works fine:

$ tmp=/folder1/This Folder Here/randomfile.abc
$ echo "$tmp" | sed -e 's/ /\\ /g'
/folder1/This\ Folder\ Here/randomfile.abc

But as soon as I pass it to a variable, sed no longer replaces the space with a backslash:

$ tmp=/folder1/This Folder Here/randomfile.abc
$ location=`echo "$tmp" | sed -e 's/ /\\ /g'`
$ echo $location
/folder1/This Folder Here/randomfile.abc

I'm hoping a second pair of eyes can pick up on something that I'm not.

3
  • What are you trying to do with this sed? Commented Apr 16, 2014 at 19:43
  • As per the first example, I want to add a backslash to all spaces within the variable, so 'This Folder Here', would be 'This\ Folder\ Here'. Commented Apr 16, 2014 at 19:44
  • Yes that I can see but why do you want to escape every space? Commented Apr 16, 2014 at 19:46

3 Answers 3

5

You need a couple of pairs of backslashes:

sed -e 's/ /\\\\ /g'

You seem to want to quote the input so as to use it as shell input. There is no need to use sed. You could use printf:

$ foo="a string with spaces"
$ printf "%q" "$foo"
a\ string\ with\ spaces
Sign up to request clarification or add additional context in comments.

1 Comment

That did it! I'd vote up if I had the reputation. Thanks devnull.
3

The quotes are being evaluated by bash during the assignment. You can get around this by quoting:

location="$(echo "$tmp" | sed -e 's/ /\\ /g')"

or devnull's answer (double the quotes)

Or switch to zsh to make things like this easier

% echo $tmp
/folder1/This Folder Here/randomfile.abc
% echo ${(q)tmp}
/folder1/This\ Folder\ Here/randomfile.abc

1 Comment

This also works, I derped by not using '"$('. Thanks for the update!
3

You need to use more quoting.

tmp="/folder1/This Folder Here/randomfile.abc"
location="$(echo "$tmp" | sed -e 's/ /\\ /g')"
echo "$location"

There's also a pure bash solution to insert the backslashes:

tmp="/folder1/This Folder Here/randomfile.abc"
echo "${tmp// /\\ }"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.