bash - shell 脚本 - 有没有办法将数字转换为字符?

标签 bash shell

<分区>

Possible Duplicate:
Integer ASCII value to character in BASH using printf

我想将我的整数转换为 ASCII 字符

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

int i = 97;          //97 is "a" in ASCII
char c = (char) i;   //c is now "a"

但是,有什么办法可以执行此 shell 脚本吗?

最佳答案

#!/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

编辑:

如您所见,ord() 有点棘手 -- 在整数前放置单引号。

The Single Unix Specification: "If the leading character is a single-quote or double-quote, the value shall be the numeric value in the underlying codeset of the character following the single-quote or double-quote."

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

参见 man printf(1p) .

关于bash - shell 脚本 - 有没有办法将数字转换为字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12855610/

相关文章:

linux - 映射查询字符串参数出现

bash - seq 同时使用逗号和点作为小数分隔符

php - 递归重命名文件名并转义特殊字符的 Shell 脚本?

git - 使用 git commit -a -m 时不想使用双引号

bash - 使用 shell 工具提取文件的一部分

shell - Ctrl+Backspace 的终端键代码是什么

linux - Bash_profile 文件编辑

java - 在 Java 中生成带参数的 linux 命令

bash - 逐行读取文件并将值赋给变量

linux - vCard=$(echo $REPLY | cut -d'i' -f 1) 有什么问题