Shell: How to replace something of a text with the

2019-07-18 05:33发布

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?

3条回答
Bombasti
2楼-- · 2019-07-18 05:50

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.

查看更多
女痞
3楼-- · 2019-07-18 05:52

I would write your code as the following.

timeoutvalue='timeout=2.0'
sed "s/timeout=[.0-9]*/${timeoutvalue}/" egtext
查看更多
一夜七次
4楼-- · 2019-07-18 05:56

Single quotes inhibit variable expansion.

sed 's/timeout=4.0/'"$timeoutvalue"'/g' egtext
查看更多
登录 后发表回答