如何在 Bash 中迭代所有 ASCII 字符?

问题描述 投票:0回答:6

我知道如何迭代字母表:

for c in {a..z}; do ...; done

但是我不知道如何迭代所有 ASCII 字符。有谁知道怎么办吗

linux bash ascii
6个回答
8
投票

您可以做的是从 0 迭代到 127,然后将十进制值转换为其 ASCII 值(或返回)。

您可以使用这些函数来做到这一点:

# POSIX
# chr() - converts decimal value to its ASCII character representation
# ord() - converts ASCII character to its decimal value

chr() {
  [ ${1} -lt 256 ] || return 1
  printf \\$(printf '%03o' $1)
}

# Another version doing the octal conversion with arithmetic
# faster as it avoids a subshell
chr () {
  [ ${1} -lt 256 ] || return 1
  printf \\$(($1/64*100+$1%64/8*10+$1%8))
}

# Another version using a temporary variable to avoid subshell.
# This one requires bash 3.1.
chr() {
  local tmp
  [ ${1} -lt 256 ] || return 1
  printf -v tmp '%03o' "$1"
  printf \\"$tmp"
}

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

# hex() - converts ASCII character to a hexadecimal value
# unhex() - converts a hexadecimal value to an ASCII character

hex() {
   LC_CTYPE=C printf '%x' "'$1"
}

unhex() {
   printf \\x"$1"
}

# examples:

chr $(ord A)    # -> A
ord $(chr 65)   # -> 65

5
投票

仅使用

echo
八进制转义序列的可能性:

for n in {0..7}{0..7}{0..7}; do echo -ne "\\0$n"; done

5
投票

这是我从 sampson-chen 和 mata 的答案中摘取一些内容后想出的一句话:

for n in {0..127}; do awk '{ printf("%c", $0); }' <<< $n; done

或者:

for n in {0..127}; do echo $n; done | awk '{ printf("%c", $0); }'

3
投票

以下是如何使用

awk
将整数打印为其相应的 ASCII 字符:

echo "65" | awk '{ printf("%c", $0); }'

将打印:

A

以下是如何通过这种方式迭代大写字母:

# ascii for A starts at 65:
ascii=65
index=1
total=26
while [[ $total -ge $index ]]
do
    letter=$(echo "$ascii" | awk '{ printf("%c", $0); }')
    echo "The $index'th letter is $letter"

    # Increment the index counter as well as the ascii counter
    index=$((index+1))
    ascii=$((ascii+1))
done

2
投票

好吧...如果你真的想要它们全部,并且你希望它是类似脚本的东西,我想你可以这样做:

awk 'function utf32(i) {printf("%c%c%c%c",i%0x100,i/0x100%0x100,i/0x10000%0x100,i/0x1000000) } BEGIN{for(i=0;i<0x110000;i++){utf32(i);utf32(0xa)}}' | iconv --from-code=utf32 --to-code=utf8 | grep -a '[[:print:]]'

但是这个列表相当庞大,而且不是很有用。 awk 可能不是生成从 0 到 0x110000 的二进制整数的最优雅的方式 - 如果您找到它,请替换更优雅的方式。

编辑:哦,我看到你只想要 ascii。好吧,我会让这个答案留在这里,以防其他人实际上想要所有 UTF 可打印字符。


0
投票

这取决于你所说的迭代是什么意思。请注意,

NUL
无法分配或传递给命令。

这会生成所有 ascii 字符

seq 0 127 |
 xargs printf '\\x%x ' |
 xargs printf '%b '
  • seq 0 127
    生成 0 到 127 之间的所有整数
  • xargs printf '\\x%x '
    将其转换为十六进制,用空格分隔
  • xargs printf '%b '
    将十六进制转换为字节,以空格分隔
© www.soinside.com 2019 - 2024. All rights reserved.