Santiago Esquivel
Santiago Esquivel

Reputation: 380

Bash Script: replace white space with "\ " in string

I am currently iterating for a value similar to this:

Administer PoolA servers :id=server@Pool@[email protected]

and would like to replace the white spaces with "\ " in order to have it look like this (or add \ before every whitespace):

Administer\ PoolA\ servers\ :id=server@Pool@[email protected]

I am aware regex would help me do this, but have been unsuccessful, any help would be greatly appreciated.

Upvotes: 2

Views: 6320

Answers (2)

LolPython
LolPython

Reputation: 178

mystring="Administer PoolA servers :id=server@Pool@[email protected]"
echo "$mystring" | sed "s/ /\\\ /g"
# --> Administer\ PoolA\ servers\ :id=server@Pool@[email protected]

Upvotes: 0

Barmar
Barmar

Reputation: 782130

There's no need to use a regular expression for this. You can use the bash Parameter Expansion operator for string replacement.

$ str='Administer PoolA servers :id=server@Pool@[email protected]'
$ newStr="${str// /\\ }"
$ echo "$newStr"
Administer\ PoolA\ servers\ :id=server@Pool@[email protected]

Upvotes: 5

Related Questions