「16進数の0xAAって、10進数だとどうなる?」とか思うことはよくありますよね*1。そんなとき、perlのワンライナーで、
$ perl -e 'print hex("AA")'
170
$
とかしてました。
でも、bashを使っているならprintfというコマンド(組み込みコマンド*2)があるんですよね。
$ help printf
printf: printf [-v var] format [arguments]
printf formats and prints ARGUMENTS under control of the FORMAT. FORMAT
is a character string which contains three types of objects: plain
characters, which are simply copied to standard output, character escape
sequences which are converted and copied to the standard output, and
format specifications, each of which causes printing of the next successive
argument. In addition to the standard printf(1) formats, %b means to
expand backslash escape sequences in the corresponding argument, and %q
means to quote the argument in a way that can be reused as shell input.
If the -v option is supplied, the output is placed into the value of the
shell variable VAR rather than being sent to the standard output.$
printfについては、「このシェル・ワンライナーがけっこう役立った: printfコマンドで超簡易テンプレート」で、テンプレートっぽい処理に使えることを紹介しました。もちろん、%d というフォーマット指定子も使えるので:
$ printf %d 0xAA
170
$
%x を使えば:
$ printf %x 170
aa
$
printfでは、\n という形の改行も使えるので、echoより便利です。
$ echo "Hello\nworld"
Hello\nworld$ printf "Hello\nworld"
Hello
world
$
echoで \n を使いたいなら:
$ echo $'Hello\nworld'
Hello
world$