Pregunta

I'm working on a script where I need a specific amount of unique numbers (this amount is given by a list of words) with constant 5 digits each number.

My first tries would be:

 test=`cat amount.log`

 for i in $test

       do 

           echo  $i $((RANDOM%10000+20000)) > random_numbers.log

 done

the output of this script is exactly the one, I am searching for:

word1 25439
word2 26134
word3 21741

But I don't trust the $random variable to give me a unique list, where I don't have a number more written than once. To be sure, the numbers are unique, my first attempt would be to use sort -u to get rid of duplicate entries, but this would mean that I have posibly less numbers then words in the list, or some words I will need to run the script again, to get a unique number for it.

I'll appreciate any suggestions, it needs to be done in unix/aix ksh shell.

¿Fue útil?

Solución

You could ensure that each number is really unique by looking for it back in the output file...

test=`cat amount.log`

touch random_numbers.log

for i in $test
do
        while true
        do
                num=$((RANDOM%10000+20000))
                grep $num random_numbers.log > /dev/null
                if [[ $? -gt 0 ]]
                then
                        break
                fi
        done
        echo $i $num >> random_numbers.log
done

Otros consejos

Have a look at the answers to How to generate a list of unique random strings? One of the ideas there should help you.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top