bash: How to add space in string? bash: How to add space in string? bash bash

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.


Give a try to this:

printf "%s\n" "${string}" | sed 's/-/ -/g'

It looks for - and replace it with - (space hyphen)


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"