首页 > 解决方案 > bash中的十六进制到十进制转换而不使用gawk

问题描述

输入:

cat test1.out
12 ,         maze|style=0x48570006, column area #=0x7, location=0x80000d
13 ,         maze|style=0x48570005, column area #=0x7, location=0x80aa0d
....
...
..
.

需要的输出:

12 ,         maze|style=0x48570006, column area #=0x7, location=8388621   <<<8388621 is decimal of 0x80000d
....

我只想将最后一列转换为十进制。我不能使用 gawk,因为它在我们公司的所有机器上都不可用。尝试使用 awk --non-decimal-data 但它也不起作用。想知道printf命令是否可以将最后一个单词从十六进制翻转为十进制。你还有什么可以提出的建议吗?

标签: bashawk

解决方案


这里不需要 awk 或任何其他外部命令:bash 的本机数学运算在算术上下文中正确处理十六进制值(这就是echo $((0xff))emits的原因255)。

#!/usr/bin/env bash
#              ^^^^- must be really bash, not /bin/sh

location_re='location=(0x[[:xdigit:]]+)([[:space:]]|$)'

while read -r line; do
  if [[ $line =~ $location_re ]]; then
    hex=${BASH_REMATCH[1]}
    dec=$(( $hex ))
    printf '%s\n' "${line/location=$hex/location=$dec}"
  else
    printf '%s\n' "$line"
  fi
done

您可以在https://ideone.com/uN7qNY看到它正在运行


推荐阅读