ka3ak ka3ak - 1 year ago 64
Bash Question

Replacing space with backslash and space

When I execute:

varx=$(echo "a b"|sed -r -e "s/\s/\\\ /g"); echo $varx

The output will be:

a\ \ b

But when I execute the following script with the argument
"a b"
a b

set -x
target=$(echo ${1} | sed -r -e "s/\s/_/g")
source=$(echo ${1} | sed -r -e "s/\s/\\\ /g")
mv ${source} ${target}
set +x

The output will be:

++ echo a b
++ sed -r -e 's/\s/_/g'
+ target=a_b
++ echo a b
++ sed -r -e 's/\s/\\ /g'
+ source='a\ b' 1) question
+ mv 'a\' b a_b 2) question
mv: target ‘a_b’ is not a directory
+ set +x

3 questions:

1) Why
source='a\ b'
and not
'a\ \ b'

2) Why
mv 'a\' b a_b
and not
mv 'a\ b' a_b
according to the previously calculated

3) And how to force the script do the same that the command line version does?

Answer Source

Add double quotes to $1:

source=$(echo "${1}" | sed -r -e "s/\s/\\\ /g")
target=$(echo "${1}" | sed -r -e "s/\s/_/g")
echo mv \"${source}\" \"${target}\"

In your script, the echo command process a and b as parameters. With double quotes, $1 is not splitted.

To illustrate :

$ echo one     two
one two
$ echo "one     two"
one     two