2012-10-29 22 views

回答

7

你可以做的是迭代fr om 0到127,然後將十進制值轉換爲其ASCII值(或返回)。

可以使用these功能來做到這一點:

# 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 
+0

請注意,0-31通常不被認爲是「可打印的」,除了第e空格字符(回車符,換行符,水平和垂直製表符)。 – twalberg

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可打印字符。

5

只使用echo小號八進制轉義序列一種可能性:

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

這裏是我想出了一個班輪採取從桑普森臣的一些作品和馬塔的答案:

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); }'