views:

35

answers:

3

I saved a value by shell command: For example:

timeoutvalue=`echo "timeout=2.0"`

And I have to grep the value of timeout from another text, and replace it with this timeoutvalue. For example, the text is egtest:

<host ip="255.255.255.0" name="testhost" description="hostfortest" connection="xmlrpc" timeout=4.0/>

I want to grep the value of timeout from the above text and replace the value of timeout=4.0 by timeout=2.0(the value I saved as variable by shell command).

My problem is: (1)for a simple test, I want to replace the value of timeout=4.0 with $timeoutvalue. So my command is:

sed 's/timeout=4.0/$timeoutvalue/g' egtext.

But it seems the text become:

<host ip="255.255.255.0" name="testhost" description="hostfortest" connection="xmlrpc" $timeoutvalue/>

Could anybody tell me why it is wrong?

(2)For this problem, I have to first grep timeout=4.0 from the text, and replace the value 4.0 to the saved variable value(in my example:2.0). I thought but I don't know which command to use to realize this(awk? sed?) Because the filed of the text isn't certain,(for example, in this text, timeout is in $5, but maybe in another text, it maybe changed into $6). I mean it may be changed into:

<host ip="255.255.255.0" name="testhost" description="hostfortest" connection="xmlrpc" type="onebox" timeout=4.0/>

Could anybody help me with this?

+1  A: 

Single quotes inhibit variable expansion.

sed 's/timeout=4.0/'"$timeoutvalue"'/g' egtext
Ignacio Vazquez-Abrams
lgnacio, thanks for your method and quick answer.But could you please tell me way we use another Single quotes besides the Double quotes of $timeoutvalue?Thanks.
zhaojing
+1  A: 

Single quote does not allow variable interpolation, so use double quotes as:

sed "s/timeout=4.0/$timeoutvalue/g" egtext

EDIT:

Consider

who='world'
echo "Hello $who" # prints Hello world
echo 'Hello $who" # prints Hello $who

as seen single quotes does not allow variable substitution. It treats $who literally as a dollar followed by who. But double quote behaves differently, when it sees $who it realizes that who is a variable and replaces $who with its value.

codaddict
codaddict,thanks a lot for your answer.It seems I still haven't fully acknowledge the difference betwween Single quote and Double quote.Thanks.
zhaojing
+1  A: 

I would write your code as the following.

timeoutvalue='timeout=2.0'
sed "s/timeout=[.0-9]*/${timeoutvalue}/" egtext
z1x2
z1x2, many thanks for your nice answer.In fact, its just what I want.
zhaojing