Reputation: 55
I'm using sed to substitute a random 10 digit string of numbers for a certain field in a file, which I can successfully do. However, the same random 10 digit string of numbers are used for each substitution sed performs which is unacceptable in this case. I need a new random 10 digit string of numbers for every substitution sed performs. Here's what I have so far:
#!/bin/bash
#
#
random_number()
{
for i in {1}; do tr -c -d 0-9 < /dev/urandom | head -c 10; done
}
while read line
do
sed -E "s/[<]FITID[>][[:digit:]]+/<FITID>$(random_number)/g"
done<~/Desktop/FITIDTEST.QFX
Here's a sample of what the original FITIDTEST.QFX file looks like:
<FITID>1266821191
<FITID>1267832241
<FITID>1268070393
<FITID>1268565193
<FITID>1268882385
<FITID>1268882384
And here is the output after executing the script:
<FITID>4270240286
<FITID>4270240286
<FITID>4270240286
<FITID>4270240286
<FITID>4270240286
<FITID>4270240286
I need those 10 digit numbers to be different for each field. I thought the "while loop" would force sed to call the random_number() function each time but apparently it's called once and the value is stored and used repeatedly. Is there anyway to avoid that? Any help is greatly appreciated!
Upvotes: 5
Views: 1140
Reputation: 203899
Just use awk:
$ cat tst.awk
BEGIN { srand() }
{
sub(/[0-9]+/,sprintf("%010d",rand()*10000000000))
print
}
$ awk -f tst.awk file
<FITID>3730584119
<FITID>1473036092
<FITID>8390375691
<FITID>6700634479
<FITID>8379256766
<FITID>6583696062
$ awk -f tst.awk file
<FITID>7844627153
<FITID>0141034890
<FITID>9714288799
<FITID>0911892354
<FITID>8916456168
<FITID>4187598430
Upvotes: 2
Reputation: 785406
Your sed
is replacing all the lines with matching pattern not just one line hence at the end of loop you are seeing same number in replacement.
You can use:
while read line; do
sed -E "/<FITID>/s/<FITID>[[:digit:]]+/<FITID>$(random_number)/" <<< "$line"
done < ~/Desktop/FITIDTEST.QFX > _tmp_
Output:
cat _tmp_
<FITID>9974823224
<FITID>1524680591
<FITID>7433495381
<FITID>6642730759
<FITID>9653629434
<FITID>1325816974
Upvotes: 1