XML : Conditional find / replace in bash shell

My issue should be rather simple, and I'm guessing where I'm failing is syntax related. I'm looking to write a simple shell script which manipulates an XML file in the following way.

The data points inside each tag will be numeric values. These should all be positive, so if there exists a negative value inside any tag within the XML file, I would like to replace it with a zero. For example, the following XML file - call it "file.xml"

  <tag1>19</tag1>  <tag2>2</tag2>  <tag3>-12</tag3>  <tag4>37</tag4>  <tag5>-41</tag5>    

should be replaced with

  <tag1>19</tag1>  <tag2>2</tag2>  <tag3>0</tag3>  <tag4>37</tag4>  <tag5>0</tag5>         

My thinking on this would be if I grepped any instance of the string ">-*<" in the file and used sed to replace it with >0< as follows.

  #!/bin/bash  STRING=">-*<"  if grep -xq "$STRING" file.xml  then  sed -i 's/$STRING/>0</g' file.xml  else  echo "that string was not found in the file"  fi    

However all I'm getting in return is the echo string "that string was not found in the file" being returned, even tho I have included negative values in the file. Does the "" not take into account any string following the minus sign in this example? Naturally there can be any number following the minus sign, so i'm thinking my problem is how I've defined the variable: STRING=">-<".... Any pointers in the right direction would be greatly appreciated. Thanks in advance.

No comments:

Post a Comment