bash 从linux shell中的文本文件生成二进制文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12550702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
generate a binary file from a text file in linux shell
提问by Alcott
I have a text file a.txt, inside which each line consists of 2 numbers, looks like this:
我有一个文本文件 a.txt,其中每行由 2 个数字组成,如下所示:
1234 5678
Now I want to convert a.txt's content from text into binary, which means the numbers won't be text anymore, but binary representation, which can be viewed by od -tu4.
现在我想将 a.txt 的内容从文本转换为二进制,这意味着数字不再是文本,而是二进制表示,可以通过od -tu4.
How can I do that via bash?
我怎样才能做到这一点bash?
回答by James
Here is a shell script that uses AWK to do what you want. Put the following into a file (hex2bin.awk):
这是一个 shell 脚本,它使用 AWK 来做你想做的事。将以下内容放入文件 (hex2bin.awk):
#!/usr/bin/awk -f
function dec2bin(n){
for(i=0;i < 4; i++){
printf("%c", n % 256);
n = int(n / 256);
}
}
{ dec2bin(); dec2bin();}
Make the file executable (chmod a+x hex2bin.awk)
使文件可执行 ( chmod a+x hex2bin.awk)
Then run it:
然后运行它:
./hex2bin.awk a.txt | od -tu4
0000000 1234 5678
0000010
This reads in two columns of decimal numbers represented in ASCII and prints them out into 32-bit little endian binary.
这将读取以 ASCII 表示的两列十进制数字,并将它们打印为 32 位小端二进制。

