【发布时间】:2018-05-16 15:17:01
【问题描述】:
如何使用 Bash 和/或常见的 Linux 命令行实用程序将文本字符串转换为 UTF-8 编码字节?例如,在 Python 中可以这样做:
"Six of one, ½ dozen of the other".encode('utf-8')
b'Six of one, \xc2\xbd dozen of the other'
有没有办法在纯 Bash 中做到这一点:
STR="Six of one, ½ dozen of the other"
<utility_or_bash_command_here> --encoding='utf-8' $STR
'Six of one, \xc2\xbd dozen of the other'
【问题讨论】:
-
避免在 cmets 中回答问题。
-
bash 没有明确的“文本字符串”与“字节”区别。当您使用
STR="Six of one, ½ dozen of the other"时,它已经 基本上是一个字节列表(更准确地说是C string),可能是UTF-8 编码,也可能是其他编码。试试echo "$STR" | od -x,您可能会在结果中看到“bdc2”。所以我不太清楚你想在这里完成什么。
标签: bash shell encoding command-line utility