6

I have a string like this:

string="aaa-bbb"

But I want to add space before char '-', so I want this:

aaa -bbb

I tried a lot of things, but I can't add space there. I tried with echo $string | tr '-' ' -', and some other stuff, but it didn't work...

I have Linux Mint: GNU bash, version 4.3.8(1)

Marta Koprivnik
  • 385
  • 2
  • 3
  • 10

5 Answers5

12

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.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
2

Bash has builtin string substitution.

$ string="aaa-bbb"
$ result="${string/-/ -}"
$ echo "$result"
aaa -bbb

Alternatively, you can use sed or perl:

$ string="aaa-bbb"
$ result=$(sed 's/-/ -/' <<< $string)
$ echo "$result"
aaa -bbb
$ result=$(perl -pe 's/-/ -/' <<< $string)
$ echo "$result"
aaa -bbb
Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
1

Give a try to this:

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

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

Jay jargot
  • 2,745
  • 1
  • 11
  • 14
1

tr can only substitute one character at a time. what you're looking for is sed:

echo "$string" | sed 's/-/ -/'

webb
  • 4,180
  • 1
  • 17
  • 26
1

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"

Community
  • 1
  • 1