views:

23

answers:

2

Is there an awk-like or sed-like command line hack I can issue to generate a list of all keyboard characters (such as a-zA-z0-9!-*, etc)? I'm writing a simple Caesar cipher program in my intro programming class where we do the rotation not through ASCII values, but indexing into an alphabet string, something like this:

String alphabet = "abcdefghijklmnopqrstuvwxyz";

for (int pos = 0; pos < message.length(); pos++) {
  char ch = message.charAt(pos);
  int chPos = alphabet.indexOf(ch);
  char cipherCh = alphabet.charAt(chPos+rotation%alphabet.length());
  System.out.print(cipherCh);
}

Clearly I can write a loop in some other language and print all ASCII values, but I'd love something closer to the command line as flashier example.

+1  A: 

Is this what you're looking for:

awk 'END {for (i=33; i<=126; i++) printf("%c",i); print ""}' /dev/null

This generates:

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

I chose the range from 33 to 126 as the printable chars. See ascii man page

glenn jackman
Thanks, this is great!
Rich
@Rich, in reality, you only ever need to do this once. You can hardcode the string in your program -- no need to do it every time.
glenn jackman
You can eliminate `/dev/null` if you change `END` to `BEGIN`.
Dennis Williamson
@glenn Exactly, I just wanted to demonstrate some programmer workbench sort of functionality on the shell.
Rich
thanks @Dennis.
glenn jackman
+1  A: 

This is pure shell, no externals:

$ for i in {32..126}; do printf \\$(($i/64*100+$i%64/8*10+$i%8)); done
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

It converts decimals to octals and prints the corresponding character.

It works in Bash and ksh, dash and ash (if you use $(seq 32 126) instead of {32..126}) and zsh (if you use print -n instead of printf).

Dennis Williamson