views:

35

answers:

2

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:-)

+1  A: 
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.
codaddict
codaddict, thanks again for your detailed information.Indeed, I didn't though up to use regex to realize this.I just begin to learn shell. Many thanks for your detailed information for both this question and last question!
zhaojing
+1  A: 

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<&-
ghostdog74
ghostdog74, thanks again for your nice and helpful answer!And it works:-)Your script helps me learn much more.I just begin to learn shell, thanks for your help!
zhaojing