AZ 또는 az 범위의 ASCII 문자를 요청하고 동등한 숫자 값을 반환하는 쉘 스크립트를 작성하려고합니다. 예를 들어 출력은 다음과 같습니다.
scarlet$ Please type a character between A and Z or between a and z:
scarlet$ A
scarlet$ The decimal value of A is: 65
내 시도 :
#!/bin/bash
echo Enter a letter:
read A
echo -n ${A} | od -i | head -1 | cut -b 10- | tr -d " "
답변
POSIX : printf a | od -A n -t d1
펄 : perl -e 'print ord($ARGV[0])' a
UTF-8 로케일 인 경우 UTF-8에 대처하는 Perl : perl -C255 -e 'print ord($ARGV[0])' œ
답변
POSIX :
$ printf %d\\n \'a
97
또한 bash 4.0 이상 및 zsh에서 비 ASCII 문자와 함께 작동합니다.
$ printf %x\\n \'あ
3042
recode ..dump
16 진 코드 포인트를 보는 데 사용할 수도 있습니다 .
$ printf aあ|recode ..dump
UCS2 Mne Description
0061 a latin small letter a
3042 a5 hiragana letter a
답변
아마도:
#!/bin/bash
echo -n "Enter a letter:"
read A
echo ${A}|od -t d1|awk '{printf "%s",$2}';echo
건배
답변
지금까지 bash와 소문자를 사용하는 od-less 솔루션. z
여기서 검색된 문자 s
입니다. i=97
ascii (a) = 97이기 때문에. 나머지는 분명하다.
z=s
i=97
for c in {a..z}
do
[ "$c" = "$z" ] && echo $i && break || ((i+=1))
done
물론 한 줄에 넣을 수도 있습니다. 여기 몇몇 semmicolons ;;;;;
가 있습니다 : (충분해야합니다)
답변
od -t d1
당신이 그것을 시도하십시오 . 다른 출력 형식은 매우 이상합니다.
예를 들어 머리와 절단이 필요하지 않습니다.
printf "A" | od -t d1 | read addr num && echo $num
답변
당신이 이것을하는 프로그램을 원하고 이것을 운동으로하지 않는다면, 이것을하는 프로그램 ascii
이 있습니다. 배포판은 http://www.catb.org/~esr/ascii/ 에서 가져 오지 않은 경우 이미 패키지로 제공 할 수 있습니다 .
답변
# Get one character per loop, until the user presses <Enter>
while true ; do
read -n 1 c
(( ${#c} == 0 )) && break # Exit the loop. Input length is 0
# ie. The user has pressed Enter
#
if [ \( ! "$c" \< "a" -a ! "$c" \> "z" \) \
-o \( ! "$c" \< "A" -a ! "$c" \> "Z" \) ]
then
val=($(ascii -s $c)) # build an array of ascii info for this char
echo " ... The decimal value of $c is: ${val[1]}"
else
echo -n $'\r \r' # overwrite the invalid character
fi
done