replace space with the help of sed

Hi,

i have below string -

mynameis arpit

i want output like below -

mynameis\ arpit

that i am getting from below -

temp='mynameis arpit'
echo $temp|sed 's/[ ]/\\ /g'      -->  mynameis\ arpit

now i am doing -

abc=`echo $temp|sed 's/[ ]/\\ /g'`
echo $abc                                   --> mynameis arpit

why the value of abc is not having backslash ??
please help me soon..

thanks in advance?:frowning:

abc="`echo $temp|sed 's/ /\\\ /g'`"
echo $abc
mynameis\ arpit

# or

abc="$(echo $temp|sed 's/ /\\ /g')"
echo $abc
mynameis\ arpit

Seems the backticks need another backslash to preserve the backslash ie. 3 of them. When using $() instead it's ok with 2. Not quite sure why it is like that but hopefully somebody else can explain it. I added double quotes just to make sure the space in between will not issue a problem.
The square brackets are not needed as they represent a group of characters. You only have 1 single char.

1 Like

Thanks a lot..it works.