无法在 Mac OSX 上将(表情符号的)十六进制值打印为 unicode

Can't print hex values (of emojis) to unicode on Mac OSX

我试图在 OSX 和 GNU/Linux.

上将十六进制值打印成 unicode emojis

我已经尝试过(例如)\U1f600'\U1f600'"\U1f600",它们在 GNU/Linux 和 echo -e 命令上都运行良好,但是在 OSX 中它根本不起作用,它只打印原始的十六进制值。我也尝试过使用 printf 命令,但它也只适用于 GNU/Linux。

如何让它在 OS X 上运行?

安装新的 bash。 :)

OSX 中的默认 bash 是过时的 3.2.57(1)-release。这是因为在 4.0 中,bash 的许可证从 GPL v2 更改为 GPL v3,因此 Apple 无法将其包含到他的 OS dist.

例如使用默认 /bin/bash

$ echo $BASH_VERSION
3.2.57(1)-release

$ echo -e '\U1f600'
\U1f600
$ printf "%b\n" "\U1f600"
\U1f600

使用 macports.org

中的 bash
$ echo $BASH_VERSION
4.4.12(1)-release
$ echo -e '\U1f600'

$ printf "%b\n" "\U1f600" 

编辑: 你可以使用 perl:

perl -CO -E 'say chr 0x1f600'
#or
perl -CO -E 'say pack 'U', 0x1f600'
#or
perl -CO -E 'say "\N{U+1F600}"'

所有印刷品


编辑 2:

emo="\N{U+1F604}"
perl -CO -E "say qq{$emo}"   #use double quotes, but isn't a good practice

更好,这将直接接受您的 \u 序列...

perl -CO -plE 's/\u(\p{Hex}+)/chr(hex())/xieg' <<< "your string"

例如:

emo='some \U1f600 and another \U1f608 here'
perl -CO -pE 's/\u(\p{Hex}+)/chr(hex())/xieg' <<< "$emo"

打印

some  and another  here

Greg's Wiki: Wooledge.org BashFAQ N 071 中的函数 chr_utf8_m 自 bash 3.1

起有效

手动进行utf8编码。

你最好去那里看看,因为完整的脚本很长。

一个简单的版本,让你掌握其中的功能是:

#!/bin/bash

chr () {
    local val
    [ "" -lt 256 ] || return 1
    printf -v val %o ""; printf "\$val"
   # That one requires bash 3.1 or above.
   }

ord() {
    # POSIX
    LC_CTYPE=C printf %d "'"
}

# examples:
chr "$(ord A)"    # -> A
ord "$(chr 65)"   # -> 65