Regex: Help with extracting a filed from the text and replace the value of the field
I have to extract a parameter from a configuration file, and replace its values with another given value. The config file is:
<host ip="200.200.200.200" name="testhost" description="test server" type="TEST_Duplex " connection="xmlrpc" xmldefaulttimeout="2.0" xmlspecifictimeout ="8.0"/>
I have to replace the value of xmldefaulttimeout="2.0"
with another value, for example: xmldefaulttimeout="4.0"
.
As in the text, xmldefaulttimeout="2.0", but in fact, the value "2.0" is not certain. It may be another uncertain value. So I have to grep the value of xmldefaulttimeout and replace it with another given value (for example:4.0).
I think I have to use sed or awk. But I'm sorry my tried commands can't realize this. Could anybody help me 开发者_运维知识库with this? Thanks! I'm sorry I just begin to learn shell:-)
input='<host ip="200.200.200.200" name="testhost" description="test server" type="TEST_Duplex " connection="xmlrpc" xmldefaulttimeout="2.0" xmlspecifictimeout ="8.0"/'
new_value='xmldefaulttimeout="4.0"'
echo $input | sed "s/xmldefaulttimeout=\"[0-9.]*\"/$new_value/"
To match any value for xmldefaulttimeout you'll have to use a regex: xmldefaulttimeout=\"[0-9.]*\"
xmldefaulttimeout=
: Matched literally\"
: To match a literal"
, you need to escape the"
to prevent premature ending of the pattern.[0-9.]
: Char class to match any digit or a period*
: zero or more of the previous char.
bash 3.2+
#!/bin/bash
new='xmldefaulttimeout="4.0"'
exec 4<"file"
while read -r line <&4
do
case "$line" in
*"xmldefaulttimeout="*)
[[ $line =~ "(.*)(xmldefaulttimeout=\".[^ \t]*\")(.*)" ]]
echo ${BASH_REMATCH[1]}${new}${BASH_REMATCH[3]}
;;
esac
done
exec 4<&-
精彩评论