如何“还原” bash中的字符串?

问题描述 投票:1回答:1

我需要使用bash命令将字符串转换为十进制ASCII码序列。示例:对于字符串'abc',所需的输出将为979899,其中,ASCII十进制代码为a = 97,b = 98和c = 99。我能够使用xxd使用ascii十六进制代码实现此目的。

printf '%s' 'abc' | xxd -p

这给了我结果:616263其中,ASCII十六进制代码中a = 61,b = 62和c = 63。

是否有等同于xxd的结果以ascii十进制代码而不是ascii十六进制代码给出?

linux bash hexdump
1个回答
0
投票

导致此问题烦人的是,当从十六进制转换为十进制时,必须对字符进行管线处理。因此,由于某些字符的十六进制表示形式比其他字符更长,因此您无法从char到hex到dec进行简单转换。

这两种解决方案均与Unicode兼容,并使用字符的代码点。在两种解决方案中,为了清楚起见,都选择了换行符作为分隔符。将其更改为'',不使用分隔符。

重击
sep='\n'
# Create a char array (See ACK.1)
charAry=($(printf 'abc🎶' | grep -o .))
for i in "${charAry[@]}"; do
  # Echoes decimal representation of one character (See ACK.2)
  printf "%d$sep" "'$i"
done && echo
97
98
99
127926

Python

这里,我们使用列表推导将每个字符转换为十进制数字(ord),将其作为字符串连接并打印。

printf '%s' 'abc🎶' | python -c "
import sys
stdin = sys.stdin.read()
sep = '\n'
print(sep.join([str(ord(i)) for i in stdin]))"
97
98
99
127926

ACK

  1. Split a string into character array in bash
  2. ord and chr in Bash
© www.soinside.com 2019 - 2024. All rights reserved.