62

I need to create a text file which should contain random text data that can be read by human. I know that we can use /dev/urandom and /dev/random for getting random data. But it is not readable by humans. I need to create a file which contains random text format. Is there any way to do that?

2

6 Answers 6

137

We can do it by following command

base64 /dev/urandom | head -c 10000000 > file.txt

It creates a file with name file.txt size of 10 MB.

3
  • 4
    This great, it also adds a newline every 76 characters too.
    – wisbucky
    Aug 28, 2019 at 21:29
  • use the -w 0 flag to base64 if you do NOT want those newlines. This will put everything on one line May 11, 2020 at 0:10
  • head -c 10485760 to get exactly 10MB
    – konchy
    Jul 18 at 6:42
17

get the output of:

tr -dc A-Za-z0-9 </dev/urandom 

and pipe it to a file.

You can use head command with -c or -n to limit the file size

example to generate a 1kB file a.txt:

tr -dc A-Za-z0-9 </dev/urandom | head -c 1024 > a.txt
1
  • You can also use [:alnum:] instead of A-Za-z0-9. Also, if you want spaces and newlines sprinkled in, you can do this variation: tr -dc '[:alnum:] \n' ...
    – wisbucky
    Aug 28, 2019 at 22:03
6

The wamerican package provides a dictionary of words available under /usr/share/dict/words.

You can use the following trick to use these:

cat /usr/share/dict/words | sort -R | head -1024 > file.txt

Note that you don't specify the geometry (how many words per line, how many lines?)

5

If you don't have /dev/urandom (because maybe you're using a GitBash console), you can use:

openssl rand 33000 -base64 -out dump.txt
1
  • just to highlight that openssl will generate an encrypted file
    – Mariam
    May 7 at 20:33
4

base64 seems to only output alphanumeric characters plus / and +.

I like this to get more "punctuation" characters, like

'[:punct:]'
  Punctuation characters; in the 'C' locale and ASCII character
  encoding, this is ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \
  ] ^ _ ` { | } ~

So use this:

'[:graph:]'
     Graphical characters: '[:alnum:]' and '[:punct:]'

and use tr to remove single quotes ' backticks ` and backslashes \

tr -dc '[:graph:]' < /dev/urandom | tr -d \''\\'\` | head -c [size]

the -c size option to head can have a multiplier suffix: b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024, GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.

2

improved version of the suggestion from Clement (above):

shuf -n 100 /usr/share/dict/words | fmt -w 72

adjust the "-n" and "-w" arguments for total number of words and line length, respectively.

this version eliminates the excessive number of proper nouns and possessives in the word list:

(sed -e "/^[A-Z]/d" -e "/'s\$/d" | shuf -n 100 | fmt -w 72) </usr/share/dict/words

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .