Passing SED replaces arguments in a BASH variable

I am trying to pass a variable with spaces to it using BASH, and in the tooltip 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 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 hope that a second pair of eyes can raise what I do not know.

+4
source share
3 answers

You will need a pair of backslashes:

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

It seems you want to quote the input in order to use it as shell input. No need to use sed. You can use printf:

$ foo="a string with spaces"
$ printf "%q" "$foo"
a\ string\ with\ spaces
+5
source

You need to use more citation.

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

There is also a clean solution bashfor inserting backslashes:

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

bash . , :

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

devnull ( )

zsh, -

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

Source: https://habr.com/ru/post/1536856/


All Articles