Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 950
Marta Koprivnik Avatar asked Dec 08 '22 22:12

Marta Koprivnik


2 Answers

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.

like image 79
Jeff Bowman Avatar answered Jan 04 '23 18:01

Jeff Bowman


Give a try to this:

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

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

like image 35
Jay jargot Avatar answered Jan 04 '23 19:01

Jay jargot