bash - 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命令是否可以将最后一个单词从十六进制翻转为十进制。你还有什么可以提出的建议吗?
解决方案
这里不需要 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
推荐阅读
- java - 弹性搜索安装中的 IndexFormatTooNew 异常 (6.5.4)
- json - 将 JSON 对象输出到单独的行
- c# - 当我在查询字符串参数中发送逗号时,twitter api“更新/状态”返回 401
- c++ - 使用 gcc 而不是 g++ 输出二进制文件的大小更小
- javascript - 在子页面点击图片加载视频
- machine-learning - 图像像素可以存储在一维数组中吗?
- google-apps-script - Google Meet startTimeCode 使用,是否可以从电子表格单元格中查找?
- maven - 以管理员身份运行 shell 时无法识别 Maven
- r - Rstudio:使用 for 循环求解方程
- ios - 如何使用 SwiftUI 在导航栏上添加按钮