Search code examples
stringbashspaces

bash: How to add space in string?


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)


Solution

  • 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.