简体   繁体   中英

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.

Try this:

STRING=">-.*<"

or better yet:

STRING=">-[0-9]*<"

In general, the * means 'any number of the last character/class of characters', so .* matches any string, [0-9]* any string consisting only of digits. Your expression would have matched '><', '>-<', '>--<', '>---<' and so on.

cat aaa.txt
<tag1>19</tag1>
<tag2>2</tag2>
<tag3>-12</tag3>
<tag4>37</tag4>
<tag5>-41</tag5>

replace negatives with zero and write to a new file

sed 's/-[0-9][0-9]*/0/' aaa.txt > a2.txt

check the new file

cat a2.txt
<tag1>19</tag1>
<tag2>2</tag2>
<tag3>0</tag3>
<tag4>37</tag4>
<tag5>0</tag5>
>-[0-9]+<

是一个或多个字符,是更好的选择

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM