bash: How to add space in string?
No need to call sed
, use string substitution native in BASH:
$ foo="abc-def-ghi"$ echo "${foo//-/ -}"abc -def -ghi
Note the two slashes after the variable name: the first slash replaces the first occurrence, where two slashes replace every occurrence.
You are asking the shell to echo an un-quoted variable $string
.
When that happens, spaces inside variables are used to split the string:
$ string="a -b -c"$ printf '<%s>\n' $string<a><-b><-c>
The variable does contain the spaces, just that you are not seeing it correctly.Quote your expansions
$ printf '<%s>\n' "$string"<a -b -c>
To get your variable changed from -
to -
there are many solutions:
sed: string="$(echo "$string" | sed 's/-/ -/g')"; echo "$string"
bash: string="${string//-/ -}; echo "$string"