shell脚本 - 有没有什么方法可以将数字转换为char?

nat*_*lus 4 bash shell

可能重复:
使用printf对BASH中的字符进行整数ASCII值

我想将整数转换为ASCII字符

我们可以像这样在java中转换:

int i = 97;          //97 is "a" in ASCII
char c = (char) i;   //c is now "a"
Run Code Online (Sandbox Code Playgroud)

但是,有没有办法做这个shell脚本?

Rah*_*tam 18

#!/bin/bash
# chr() - converts decimal value to its ASCII character representation
# ord() - converts ASCII character to its decimal value

chr() {
  printf \\$(printf '%03o' $1)
}

ord() {
  printf '%d' "'$1"
}

ord A
echo
chr 65
echo
Run Code Online (Sandbox Code Playgroud)

编辑:

如你所见ord()有点棘手 - 在整数前放一个引号.

单Unix规范:"如果前导字符是单引号或双引号,则该值应为单引号或双引号后字符的基础代码集中的数值." 看printf()

(摘自http://mywiki.wooledge.org/BashFAQ/071)


P.P*_*.P. 6

declare -i i=97
c=$(printf \\$(printf '%03o' $i))
echo "char:" $c
Run Code Online (Sandbox Code Playgroud)