Search code examples
shellhexasciiterminfo

Characters to hex


I need some help in Shell scripting. I have a folder with single-letter folder names starting with 1 and ending with the small letter z: [1-9A-Za-z]. Now, I want to rename the folders to its hexadecimal value: 1 to 31 ... z to 7A.

I wanted to fix this with a for loop, but now I'm stuck here. I had never programmed with Shell, but with C and ASM.

[Edit]: Open your Terminfo folder. On OS X (10.9.1): /usr/share/terminfo. There you can see hex values. Now, on my iPhone, they are in single ASCII characters. Therefore the terminal can't find any file.


Solution

  • In any appropriate directory, you can try:

    $ mkdir terminfo
    $ cd terminfo
    $ mkdir {0..9} {a..z}
    $ ls
    0   3   6   9   c   f   i   l   o   r   u   x
    1   4   7   a   d   g   j   m   p   s   v   y
    2   5   8   b   e   h   k   n   q   t   w   z
    $ for d in ?; do mv "$d" $(printf "%2X" "'$d'"); done
    $ ls
    30  33  36  39  63  66  69  6C  6F  72  75  78
    31  34  37  61  64  67  6A  6D  70  73  76  79
    32  35  38  62  65  68  6B  6E  71  74  77  7A
    $
    

    If you use echo mv instead of just mv, you can see the operations the shell does. You can use %2x in place of %2X to get names like 7a, which matches what I see in /usr/share/terminfo on my machine (but the file system is case-preserving and case-insensitive, so the upper-case should work). You might also consider using ln -s instead of mv; that way, you have both the old names and the new names available, so old code and new code should be happy.

    Tested on Mac OS X 10.9.1 Mavericks.