Unix & Linux: Bash script to get ASCII values for alphabet (8 Solutions!!)

preview_player
Показать описание
Unix & Linux: Bash script to get ASCII values for alphabet

The Question: How do I get the ASCII value of the alphabet?
For example, 97 for a?

Solutions: Please watch the whole video to see all solutions, in order of how many people found them helpful

== This solution helped 76 people ==
Define these two functions (usually available in other languages):
chr() {
[ "$1" -lt 256 ] || return 1
printf "\$(printf '%03o' "$1")"
}

ord() {
LC_CTYPE=C printf '%d' "'$1"
}
Usage:
chr 65
A

ord A
65

== This solution helped 14 people ==
This works well,
echo "A" | tr -d "n" | od -An -t uC

echo "A" ### Emit a character.
| tr -d "n" ### Remove the "newline" character.
| od -An -t uC ### Use od (octal dump) to print:
### -An means Address none
### -t select a type
### u type is unsigned decimal.
### C of size (one) char.
exactly equivalent to:
echo -n "A" | od -An -tuC ### Not all shells honor the '-n'.

== This solution helped 13 people ==
If you want to extend it to UTF-8 characters (assuming you're in a UTF-
8 locale):
$ perl -CA -le 'print ord shift'
128520

$ perl -CS -le 'print chr shift' 128520

With bash, ksh or zsh builtins:
$ printf "U$(printf %08x 128520)n"

== This solution helped 20 people ==
You can see the entire set with:
$ man ascii
You'll get tables in octal, hex, and decimal.

== This solution helped 6 people ==
I'm going for the simple (and elegant?) Bash solution:
for i in {a..z}; do echo $(printf "%s %d" "$i" "'$i"); done
For in a script you can use the following:
CharValue="A"
AscValue=`printf "%d" "'$CharValue"
Notice the single quote before the CharValue. It is obligated...

Рекомендации по теме
join shbcf.ru