开发者

Shell: How to replace something of a text with the saved variable value

开发者 https://www.devze.com 2023-01-13 21:26 出处:网络
I saved a value by shell command: For example: timeoutvalue=`echo \"timeout=2.0\"` And I have to grep the value of timeo开发者_JAVA技巧ut from another text, and replace it with this timeoutvalue.

I saved a value by shell command: For example:

timeoutvalue=`echo "timeout=2.0"`

And I have to grep the value of timeo开发者_JAVA技巧ut 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?


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.


Single quotes inhibit variable expansion.

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


I would write your code as the following.

timeoutvalue='timeout=2.0'
sed "s/timeout=[.0-9]*/${timeoutvalue}/" egtext
0

精彩评论

暂无评论...
验证码 换一张
取 消