views:

92

answers:

3

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?

G-Man

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

+1  A: 
cat somefile|head -c `head -c 3 /dev/random |hexdump -d|cut -f4 -d ' '|head -n1`
Grant Johnson
+2  A: 

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.)

Jefromi
This is copying the entire contents of the input file.
GeoffreyF67
It should be pointed out that `$RANDOM` is a builtin automatic variable in Bash which contains pseudorandom numbers in the range 0-32767.
Dennis Williamson
+1  A: 

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
nsayer
Bash has a builtin RANDOM variable
Jürgen Hötzel
@Jürgen: Good to know. I use tcsh, which so far as I know, does not.
nsayer