Home > Blockchain >  How can I generate specified number of integers in Linux?
How can I generate specified number of integers in Linux?

Time:10-12

I found a lot of questions/answers related to this issue but I failed to choose what exactly what I need.

How can I generate specified number of integers?

#!/bin/sh
count=$1
# TODO: print $count integers to the console

which prints random integers one at a line.

$ generate.sh 32768
1
32
-47
9
-2
31
...
$

So that I can pipe the output to a file.

sh ./generate.sh 32768 > random_intengers.txt

I'm currently doing this.

#!/bin/sh
count=$1
for i in $(seq $count); do
    echo $SRANDOM
done

Is it good enough? Any other more efficient way using od or some?

Integer range is not a problem as long as not bigger than 32 bit, signed will be better

CodePudding user response:

I would use hexdump and /dev/urandom if they are available:

$ count=5
$ hexdump -n $((4*count)) -e '/4 "%d\n"' /dev/urandom > random_integers.txt
$ cat random_integers.txt
535142754
455371601
-323071241
-1154116530
1841746137

Explanation:

  • -n $((4*count)) reads 4*count bytes from /dev/urandom.
  • -e '/4 "%d\n"' specifies a format string that uses 4 bytes at a time (/4) and prints them as an integer followed by a newline ("%d\n").

CodePudding user response:

If you have the jot command available you could do this:

$ jot -r 10 0 1000
89
664
188
588
785
426
723
221
833
265

Prints 10 random (-r) numbers between 0 and 1000. And it can also generate decimal numbers:

$ jot -r 10 0 1000.0
189.9
15.6
989.6
139.9
777.0
18.1
285.3
574.8
201.0
312.1

Or signed:

$ jot -r 10 -1000 1000.0
-551.5
-65.0
634.3
-814.6
881.2
-713.7
422.1
390.3
674.2
-750.9

CodePudding user response:

python based solution below

import sys
from random import randrange
count = int(sys.argv[1]) if len(sys.argv) > 1 else 1000

for x in range(0,count):
  print(randrange(100000))
  •  Tags:  
  • bash
  • Related