bash shell 脚本 - 有没有办法将数字转换为字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12855610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
shell script - is there any way converting number to char?
提问by natrollus
Possible Duplicate:
Integer ASCII value to character in BASH using printf
I want to convert my integer number to ASCII character
我想将我的整数转换为 ASCII 字符
We can convert in java like this:
我们可以像这样在java中转换:
int i = 97; //97 is "a" in ASCII
char c = (char) i; //c is now "a"
But,is there any way in to do this shell scripting?
但是,有什么办法可以做这个 shell 脚本吗?
回答by Rahul Gautam
#!/bin/bash
# chr() - converts decimal value to its ASCII character representation
# ord() - converts ASCII character to its decimal value
chr() {
printf \$(printf '%03o' )
}
ord() {
printf '%d' "'"
}
ord A
echo
chr 65
echo
Edit:
编辑:
As you see ord()
is a little tricky -- putting a single quote in front of an integer.
如您所见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."
单一 Unix 规范:“如果前导字符是单引号或双引号,则该值应是单引号或双引号之后字符的底层代码集中的数值。”
(Taken from http://mywiki.wooledge.org/BashFAQ/071).
(取自http://mywiki.wooledge.org/BashFAQ/071)。
See man printf(1p).
回答by P.P
declare -i i=97
c=$(printf \$(printf '%03o' $i))
echo "char:" $c