【问题标题】:Convert text to bytes from Bash shell?从 Bash shell 将文本转换为字节?
【发布时间】: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


【解决方案1】:

Perl 来救援!

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

/e 修饰符允许将代码包含到 s/// 替换的替换部分中,在这种情况下,通过 sprintford 转换为十六进制。

【讨论】:

    【解决方案2】:

    Python 来救援!

    alias encode='python3 -c "from sys import stdin; print(stdin.read().encode(\"utf-8\"))"'
    
    root@kali-linux:~# echo "½ " | encode
    b'\xc2\xbd \n'
    

    此外,如果您愿意,您可以使用一些 sed/awk 东西删除 b''

    【讨论】:

    • 我很感激你的努力,并且没有投票,但是 IIRC 我特别不能使用 Python 来解决这个问题,不得不依赖 bash 实用程序,我想我在问题。如果 Python 可用,另一个选项是 encode() { python3 -c "print('$1'.encode())" ; } 并调用 encode "½ "
    • 我也没有意识到您特别要求使用 bash utils/pure bash。我看到了 perl 的答案,所以给出了 python 的答案。我的坏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多