ceving
ceving

Reputation: 23876

How to generate all ASCII characters with a brace expansion?

This lists all English characters:

$ echo {A..Z}
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

But how to list all ASCII characters?

I tried this:

$ echo {\!..\~}
{!..~}

and this:

$ echo {$'!'..$'~'}
{!..~}

But both did not work. Is it possible?

Upvotes: 1

Views: 192

Answers (2)

Ed Morton
Ed Morton

Reputation: 204218

$ printf '%b\n' "$(printf '\%03o' {0..127})"



123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

To see a representation of the non-printable characters in the output from the above and the characters hidden by the effect of trying to print them as-is, you can pipe it to cat -v:

$ printf '%b\n' "$(printf '\%03o' {0..127})" | cat -v
^@^A^B^C^D^E^F^G^H
^K^L^M^N^O^P^Q^R^S^T^U^V^W^X^Y^Z^[^\^]^^^_ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~^?

To print just from the ASCII code for ! (33) to the ASCII code for ~ (126):

$ printf '%b\n' "$(printf '\%03o' {33..126})"
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

and to print from ! to ~ without having to know their numeric values:

$ printf '%b\n' "$(eval printf '\\%03o' $(printf '{%d..%d}' "'!" "'~"))"
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

which you can use with shell variables to hold the beginning and ending chars:

$ beg='!'; end='~';
$ printf '%b\n' "$(eval printf '\\%03o' $(printf '{%d..%d}' "'$beg" "'$end"))"
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Upvotes: 2

Dennis Williamson
Dennis Williamson

Reputation: 360395

This uses only one printf but a more complicated brace expansion.

printf '%b' \\x{0..7}{{0..9},{a..f}}

It also works, but not as nicely (it outputs a lot of whitespace):

echo -e \\x{0..7}{{0..9},{a..f}}

Upvotes: 3

Related Questions