Shell – How to fill a file with a stream from /dev/urandom with a specified number of lines

ddpiperandomshell-scripttext processing

I am trying to fill a file with a sequence of random 0 and 1s with a user-defined number of lines and number of characters per line.

the first step is to get a random stream of 0 and 1s:

cat /dev/urandom | tr -dc 01

then I tried to fill a file with this stream (and end the process of filling by ctrl+c)

cat /dev/urandom | tr -dc 01 > foo

when I count the numbers of lines of the so created foo file I get 0 lines.

cat foo | wc -l
0

Now I tried to control the stream, so I created a named pipe and directed the stream into it. Then I made a connection to the named pipe with the dd command in vain hope to control this way the amount of characters per line and number of lines in the file.

makefifo namedpipe
cat /dev/urandom | tr -dc 01 > namedpipe
dd if=namedpipe of=foo bs=10 count=5

the foo file got indeed filled with 50 byte of 0 and 1 , but the number of lines was still 0.

How can I solve it, I guess maybe I have to insert each number of characters a newline into the file, but if so , I do not know how.

Best Answer

How about fold? It's part of coreutils...

$ tr -dc 01 < /dev/urandom | fold -w 30 | head -n 5
001010000111110001100101101101
000101110011011100100101111000
111010101011100101010110111001
111011000000000101111110110100
110011010111001110011010100011

Or if that's not available, some flavour of awk:

$ tr -dc 01 < /dev/urandom | awk \$0=RT RS=.\{,30} | head -n 5
000100010010001110100110100111
101010010100100110111010001110
100011100101001010111101001111
010010100111100101101100010100
001101100000101001111011011000

Or you could just do something with a loop...

$ for line in $(seq 1 5)
> do
>     echo $(tr -dc 01 < /dev/urandom | head -c 30)
> done
100101100111011110010010100000
000000010000010010110111101011
010000111110010010000000010100
001110110001111011101011001001
001010111011000111110001100110

I'm sure there are other ways... I thought maybe hexdump with a custom format could do it, but apparently not... ;)

Related Question