4

So far I know, the /dev/urandom file is one of the special files, it's purpose is to generate random characters. When I execute cat /dev/urandom a stream of strange characters, some even Chinese ideograms are displayed continuously. However, if I pipe this stream of strange characters into tr with the option -dc it makes a random stream of 0 and 1 or whatever characters are put into quotation marks in tr -dc "setofcharacters".

I tried to read the manual for tr, but under -d and -c I get explanations that I do not understand or could make sense of, like

   -c, -C, --complement
          use the complement of SET1

   -d, --delete
          delete characters in SET1, do not translate

could someone please be so kind and deliver a step by step explanation of the logic behind cat /dev/urandom | tr -dc "01"

4 Answers 4

11

I think that the biggest problem is to understand what “complement” means in the description of the -c option. It refers to complement as in set theory, read about it on Wikipedia:

In set theory, a complement of a set A refers to things not in (that is, things outside of) A.

Complement of set 01 means all characters except 0 and 1. Thus, the -d option will remove all characters that are neither 0 nor 1.

3

-d means delete all caracters in SET1 and -c means use the "complement" of SET1. Combined, it means: delete all caracters that are not in SET1

Your are getting a list of characters, including 0's and 1's, and the tr -dc "01" is deleting all characters that are not in the list "01", displaying only 0s and 1s.

1

The complement option simply gives you the inverse set of the set you provide. So if you give it 01, its going to affect everything that is not a 0 or a 1 ASCII character. And the delete option will delete the selected set. So you are simply deleting everything on input that is not a 0 or 1 ASCII character.

Please understand though that these are only ASCII characters from the output of /dev/urandom, they are not the actual binary values representing the output of all the characters in /dev/urandom.

1

If you read tr manual carefully, you can explain the command easily.

The general form:

tr [option]... set1 [set2]

With your command:

tr -dc "01"

set1 contains 0 and 1. With -c option, tr will replace set1 with its complement, which mean all characters except 0 and 1.

So, the command can be interpreted as Delete all characters except zero and one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.