6

アルファベットを反復する方法を知っています:

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

しかし、すべての ASCII 文字を反復処理する方法がわかりません。誰も方法を知っていますか?

4

6 に答える 6

8

できることは、0 から 127 まで繰り返してから、10 進数値を 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
于 2012-10-29T19:10:05.823 に答える
5

echo8 進数のエスケープ シーケンスのみを使用する可能性:

for n in {0..7}{0..7}{0..7}; do echo -ne "\\0$n"; done
于 2012-10-29T22:32:08.220 に答える
3

整数を対応するASCII文字として出力する方法は次のawkとおりです。

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
于 2012-10-29T19:09:56.417 に答える
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 までの 2 進整数を生成する最も洗練された方法ではない可能性があります。見つけた場合は、より洗練されたものに置き換えてください。

編集: ああ、あなたは ascii だけを欲しがっていたようですね。まあ、他の誰かが実際にすべてのUTF印刷可能文字を必要とする場合に備えて、この回答はここにとどめておきます。

于 2012-10-29T19:32:24.727 に答える