XML- Sed Bash script... Help!

August 24, 2011 at 23:48:30
Specs: Windows 7, Core2 2.8 - 4GB
Hi ! I'm working into my first bash script to make some xml modification and it's going to make me crazy lol .. so I decide to try into this forum to take some ideas from people that really know about this!

This is my situation I've and xml file with a lots of positional values with another tags too but this are the importants tags
and this continue with differents values in the same way
I need to change all the values of x tags by new ones, particulary with random numbers.. the problem that I've is that I have succes to change that values but..... ! , sed change me the value of all the <x> </x> tags with the same value and I need that all that values were differents.. here my code


while [ $NUM -le 20 ]; do
NUM1=$(echo "scale=3;((${RANDOM})/1000)" |bc)
echo "$NUM1"
sed 's/<x>[-[:alnum:]./]\{1,\}<\/x>/<x>'$NUM1'<\/x>/' myfile.xml > newfile.xml

echo "\$NUM: $NUM"
let NUM=$NUM+1


See More: XML- Sed Bash script... Help!

Report •

August 26, 2011 at 10:20:20
awk can solve this problem, but an issue is seeding the random number generator to get a sufficient distribution. Here is my take:


awk ' BEGIN { "./myrandom.ss"| getline myseed

# change the line beginning with <x>
if($0 ~ /^<x>/)
   myrandom=(rand() * 1000)
print $0

}' myfile.xml

The random number seed, myrandom.ss, is another shell script existing in the present working directory. Here is the code:


# myrand.ss: seed the RANDOM number generator
s1=$(/bin/ps -elfy)
s2=$(head -c4 /dev/urandom | od -N2 -tu4 )
RANDOM=$(echo $s1 $s2|/usr/bin/cksum|/usr/bin/cut -b1-8)
NUM1=$(echo "scale=3;((${RANDOM})/1000)" |bc)
echo $NUM1
# end script

Check the man page on awk's internal srand() and rand() function for more information.

Report •

August 29, 2011 at 20:46:35
The problem is with your sed command. If your intent is to change the data line by line, then you need to read the file line by line and apply your change to each line before you write it to the output file. The way you are writing your script, sed will apply the last value of NUM1 to all instances of the <x> tag in the file.

Report •
Related Solutions

Ask Question