gpt4 book ai didi

bash - 从 Bash shell 将文本转换为字节?

转载 作者:行者123 更新时间:2023-12-02 17:08:45 30 4
gpt4 key购买 nike

如何使用 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'

最佳答案

Perl 助你一臂之力!

echo "$STR" | perl -pe 's/([^x\0-\x7f])/"\\x" . sprintf "%x", ord $1/ge'

/e 修饰符允许将代码包含到 s/// 替换的替换部分中,在本例中将 ord 转换为通过 sprintf 到十六进制.

关于bash - 从 Bash shell 将文本转换为字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50374576/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com