GeoffreyF67
GeoffreyF67

Reputation: 11141

Grab a random number of bytes from a file with bash?

I have a file of 256MB. I'd like to retrieve a random amount of data from this file and copy it to another file.

Is there a way to do this in bash or some other way?

Edit: choose a random number between 1 and 256 then copy that number of mb from one file to another.

Upvotes: 0

Views: 1746

Answers (3)

Cascabel
Cascabel

Reputation: 496902

This copies starting from the beginning:

# (random) blocks of one byte
dd of=output_file if=input_file ibs=1 count=$((($RANDOM % 256) + 1)M

# one block of (random) bytes
dd of=output_file if=input_file ibs=$((($RANDOM % 256) + 1)M count=1

Use the skip= option to start from somewhere else, if you want.

(My bad, forgot to specify the block size.)

Upvotes: 4

nsayer
nsayer

Reputation: 17047

If your OS has a /dev/urandom, then picking random numbers is easy:

RANDNUM=`dd if=/dev/urandom bs=1 count=1 | od -t u1 | cut -f4- -d ' ' | head -1 | sed 's/ //g'`

Once you have a random number,

dd if=input_file of=output_file bs=${RANDNUM}m count=1

Upvotes: 1

Grant Johnson
Grant Johnson

Reputation: 1244

cat somefile|head -c `head -c 3 /dev/random |hexdump -d|cut -f4 -d ' '|head -n1`

Upvotes: 1

Related Questions