简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM