3

How can I get the Unicode code point of a character in zsh?

e.g., if I have:

s=abc

How can I get the code point of s[2] (i.e. code point of "b" = 0x0062)?

2
  • Does it have to be in zsh? You can just create a script file and put python3 -c "print(ord(u'b'))" into it. BTW, the Unicode for 'b' is 98. Nov 11, 2019 at 20:18
  • 1
    @Quora Feans: I want it to be in zsh since my shell is zsh, and I don't want to have any other dependencies. 0062 in hex == 98 in decimal; I prepended 0x in my question to clarify.
    – XDR
    Nov 11, 2019 at 21:09

2 Answers 2

3

Indexing is done with ${s:start:length}, and then converted to hexadecimal using printf with %x. You can do further formatting with printf if you like.

printf '%x\n' "'${s:1:1}'"
3
  • 1
    %x converts 'b to a code point. The single quote is what makes it work. Indexing doesn't have to be done with ${s:1:1}, $s[2] works just fine. Nov 11, 2019 at 23:11
  • Is there any difference between printf '%04x\n' "'${s[2]}'" & printf "%04x\n" "'${s[2]}'"? (single vs. double quotes around first argument) I get the same output for the 2
    – XDR
    Nov 11, 2019 at 23:53
2

You can get it through the printf builtin.

With the numeric format specifiers, if the corresponding argument starts with a quote character, the numeric value of the following character is used as the number to print

To store the code point in a numeric variable:

printf -v code_point %d \'$s[2]

To print out the code point in hexadecimal notation:

printf '%04x\n' \'$s[2]
3
  • Running either of those commands in zsh 5.7.1 (x86_64-apple-darwin18.2.0) on macOS Catalina 10.15.1 results in 0, either 0 stored in code_point, or 0000 output to the console. But 0x0062 should be output.
    – XDR
    Nov 11, 2019 at 23:49
  • I think $s[2] needs to be "'$s[2]'", though I'd use "'${s[2]}'"
    – XDR
    Nov 12, 2019 at 0:53
  • 1
    @XDR Indeed I'd forgotten the quotes in the example. On the other hand I see no reason to put braces. They're just visual noise. And you only need a quote before the character, not after. Nov 12, 2019 at 8:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .