Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing SED replace arguments within a BASH variable

Tags:

bash

sed

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.

like image 684
hobbes Avatar asked Dec 20 '22 15:12

hobbes


1 Answers

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
like image 79
devnull Avatar answered Jan 05 '23 00:01

devnull