Keep spaces when using sed command in kornshell sc

2019-07-13 18:16发布

问题:

I'm having some trouble with the sed command :

I'd like to replace in a string, a single quote by two single quote
Here's my string :

04CA07807800106109XE00187200000081960          NI         0780643442        178'0700

I used this sed command to replace the single quote :

line=`echo $line | sed "s/'/''/g"`

The result is

04CA07807800106109XE00187200000081960 NI 0780643442 178''0700

As you can see, the single quote is properly replaced by two single quotes.
But I lost all the spaces between each character of my string and I really need to keep them.

Is there a way to keep those spaces with the sed command ?
I tried with a tr command and i got the same result.

Thank you for your help.

回答1:

Problem is not sed command but your unquoted variable. Use:

line=`echo "$line" | sed "s/'/''/g"`

Unquoted variable causes word splitting which results in multiple parameters to echo, resulting in single spaced words.