min*_*nto 4 linux scripting python conversion numeric-data
我需要将文本文件中的十进制值列表转换为十六进制格式,例如 test.txt 可能包含:
131072
196608
262144
327680
393216
...
Run Code Online (Sandbox Code Playgroud)
输出应该是十六进制值列表(十六进制 8 位,带前导零):
00020000
00030000
00040000
...
Run Code Online (Sandbox Code Playgroud)
输出被打印到文本文件中。如何使用 python 或 linux shell 脚本来做这个?
我错过了一个额外的操作:我需要80000000为每个创建的十六进制值添加十六进制。(算术加法,适用于已创建的十六进制值列表)。
jes*_*e_b 13
您可以使用printfand执行此操作bash:
printf '%08x\n' $(< test.txt)
Run Code Online (Sandbox Code Playgroud)
或者使用 printf 和 bc...只是...因为?
printf '%08s\n' $(bc <<<"obase=16; $(< test.txt)")
Run Code Online (Sandbox Code Playgroud)
为了将输出打印到文本文件,只需使用 shell 重定向,>如:
printf '%08x\n' $(< test.txt) > output.txt
Run Code Online (Sandbox Code Playgroud)
三个可能的解决方案(假设每一行的一组唯一的数字):
对于像 ksh、bash、zsh 这样的 shell:
printf '%08x\n' $(<infile)
Run Code Online (Sandbox Code Playgroud)
只为 bash
<file.txt mapfile -t arr; printf '%08x\n' "${arr[@]}"
Run Code Online (Sandbox Code Playgroud)
对于更简单的 shell:dash(基于 Debian 的系统中的默认 sh)、ash(busybox 模拟 shell)、yash 以及 AIX 和 Solaris 中的一些默认 shell:
printf '%08x\n' $(cat infile)
Run Code Online (Sandbox Code Playgroud)
事实上,对于像传家宝版本(Bourne 之类)这样的 shell,它需要这样写(它可以在上面列出的所有 posix shell 上工作,但我强烈建议不要使用它):
$ printf '%08x\n' `cat infile`
Run Code Online (Sandbox Code Playgroud)
了解十六进制值80000000将导致 32 位计算机上的溢出(现在不常见,但可能)。检查echo "$((0x80000000))"不打印负值。
$ for i in $(<infile); do printf '%08x\n' "$(($i+0x80000000))"; done
80020000
80030000
80040000
80050000
80060000
Run Code Online (Sandbox Code Playgroud)
使用awk:
$ awk '/[0-9]/ { printf("%08x\n", $0) }' file
00020000
00030000
00040000
00050000
00060000
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5010 次 |
| 最近记录: |