将ASCII中的Char值保存在bash变量中

时间:2018-11-29 14:42:26

标签: bash shell char ascii

我有这段代码将Dec ASCII值转换为char:

printf "\\$(printf %o $ascii_value)"

我想将其保存在var中,而不是打印它。但是,我无法以这种方式获取Char值。

root@private:/path# v=`printf "\\$(printf %o 42)"`; echo $v
$(printf 0 42)
root@private:/path# printf "\\$(printf %o 42)"
*

如何将Char值保存在变量中? 谢谢!

2 个答案:

答案 0 :(得分:4)

如果外壳程序中可用的printf支持-v选项(类似于C中的sprintf()),则可以直接使用该选项将格式化字符串的内容直接存储到变量中和 not 打印到标准输出。

printf -v char_value "\\$(printf %o $ascii_value)"

您可以通过一个简单的示例进行验证

for ascii in {65..90} {97..122}; do
    printf -v char_value "\\$(printf %o $ascii)"
    printf '%c\n' "$char_value"
done

答案 1 :(得分:1)

只需:

ascii_value=65; char="$(printf "\\$(printf "%o" "${ascii_value}")")"; echo $char
A

让此功能易于重用:

#!/usr/bin/env bash

# Gets a character from its ASCII value
# Params:
# $1: the ASCII value of the character
# Return:
# >: the character with given ASCII value
# ?: false if the ASCII value is out of the 0..127 range
ASCIIToChar() {
  [ "${1}" -lt 0 -o "${1}" -gt 127 ] && return 1
  printf "\\$(printf "%o" "${1}")"
}

# Lets demo the function above

declare -i ascii  # variable ascii of type integer
declare character # variable character

# Print a header
echo -e "ASCII\t\tCharacter"
for ascii in {65..90} {97..122}; do
  # Convert the ascii value and store the character
  character="$(ASCIIToChar "${ascii}")"

  # Print line with 2 columns ASCII and character
  echo -e "${ascii}\t\t${character}"
done

将输出:

ASCII       Character
65          A
66          B
67          C
68          D
69          E
70          F
[...]
119         w
120         x
121         y
122         z

或者将UTF-8转换为字符

# Gets a character from its UTF-8 value
# Params:
# $1: the UTF-8 value of the character
# Return:
# >: the character with given UTF-8 value
# ?: false if UTF-8 value is out of the 0..65535 range
UTF8toChar() {
  [ "$((${1}))" -lt 0 -o "$((${1}))" -gt 65535 ] && return 1;
  printf "\\u$(printf "%04x" "${1}")"
}

# Lets demo the function above

declare -i utf8   # variable utf8 of type integer
declare character # variable character

# Print a header
echo -e "UTF-8\t\tCharacter"
for utf8 in {9472..9616} # U+2500..U+259F semi-graphic
do
  # Convert the UTF-8 value and store the character
  character="$(UTF8toChar "${utf8}")"

  # Print line with 2 columns UTF-8 and character
  printf "U+%04X\t\t%s\n" "${utf8}" "${character}"
done

将输出:

UTF-8       Character
U+2500      ─
U+2501      ━
U+2502      │
U+2503      ┃
U+2504      ┄
U+2505      ┅
[...]
U+2567      ╧
U+2568      ╨
U+2569      ╩
U+256A      ╪
U+256B      ╫
U+256C      ╬
U+256D      ╭
U+256E      ╮
U+256F      ╯
U+2570      ╰
[...]