Characters to hex

714 Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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.

2
On

To rename a directories with a single-character name to the ascii hex value of that name:

for dir in [1-9A-Za-z]
do
    mv "$dir" "$(printf  "${2:-%x}" "'$dir")"
done

The above is based on code for converting ascii to hex using bash. Thus, this script converts the character given as its first argument to its ascii hexadecimal value:

#!/bin/sh
printf  "${2:-%x}\n" "'$1"

So, for example, if you put that script in an executable file called char2hex.sh:

$ bash char2hex.sh 1
31
$ bash char2hex.sh z
7a

MORE: The information below is for the first version of this question which asked for decimal values:

This script converts the character given as its first argument to its ascii decimal value:

#!/bin/sh
printf  "${3:-%d}\n" "'$1"

So, for example, if you put that script in an executable file called char2hex.sh:

$ char2hex.sh z
122