microcreat 发表于 2010-11-17 16:00:00

linux下怎样把txt文件读成自己想要的格式!

比如
xx.txt里面的文件内容是:
255,44,33,0,33
我怎么样把它读成255转换为一个字节0xff.
有没有库函数还是需要自己去转换呢?

root 发表于 2010-11-17 17:51:02

try this
sed 's/,/;/g' xx.txt | xargs echo "ibase=10;obase=8;" |bc |xargs -I "XX" echo -n "\"\0XX\""|xargs echo -e -n >xx.bin
俺只是扔块砖头,希望sed 和awk 达人搞个简单点的玉。
另外,该命令行完备性未验证,大数据量下是否正确也没验证,仅作楼主的参考。不过楼主可以试下~~~

yuphone 发表于 2010-11-17 18:22:14

楼上的shell学得真好。

atommann 发表于 2010-11-17 18:28:16

用 tcl 处理:
$ tclsh
% set str "255,44,33,033"
255,44,33,033
% set a
255 44 33 033
%
然后再转换,很多工具都可以,楼主可能说的是在 C 语言中读入文件?

root 发表于 2010-11-17 18:30:05

谢谢2楼的夸奖 ./emotion/em112.gif

楼主可以看看这个,比偶的要好很多
http://linuxwebdev.blogspot.com/2005/06/linux-hexadecimal-howto.html
(注:请使用崂山之术)
============== 以下是我的转贴 From http://linuxwebdev.blogspot.com/2005/06/linux-hexadecimal-howto.html ======================================================
Linux Hexadecimal HOWTO



There are 4 things you need to do with HEX values in LINUX

For the impatient:

1) Convert Hex to Decimal
echo 68 65 6c 6c 6f 20 77 6f 72 6c 64 |tr '' '' |sed 's/ / p /g' |sed 's/$/ p/'|awk '{print "16i "$0}'|dc |tr '\n' ' '

104 101 108 108 111 32 119 111 114 108 100

4) Convert Hex to ASCII

echo 68656c6c6f20776f726c64 |sed 's/../& /g' |tr '' '' |sed 's/ / p /g' |sed 's/$/ p/'|awk '{print "16i "$0}'|dc |tr ' ' '\n' |awk '{printf("%c",$0)}'
Even Better -

echo 68656c6c6f20776f726c64 | xxd -r -p

hello world

2)Convert Decimal to Hex
echo 87 87|tr ' ' '\n'|awk '{printf "%x ",$1}'
57 57
3) Convert ASCII to HEX

echo -n hello world |od -tx1 |cut -c8-|tr -d ' \n'
68656c6c6f20776f726c64


More Examples:


If it wasn't so simple, you could put it in a script and call it ascii2hex.sh.

This command is usefull to encode ascii text into 8 bit Hex (UCS2)
for sending the payload of a PDU sms message.

If it wasn't so simple, you could put it in a script and call it ascii2hex.sh.

echo -n "202.9.98.54:8080/CGServer/serve.jsp?id=123456" |od -tx1
0000000 32 30 32 2e 39 2e 39 38 2e 35 34 3a 38 30 38 30
0000020 2f 43 47 53 65 72 76 65 72 2f 73 65 72 76 65 2e
0000040 6a 73 70 3f 69 64 3d 31 32 33 34 35 36
0000055

Just ignore the first column or cut it out and remove the non-text characters with "| cut -c 8- |tr -d ' \n' "
3230322e392e39382e35343a383038302f43475365727665722f73657276652e6a73703f69643d313233343536

Here is a standard 8 bit ascii chart to verify the results.

x="C0 AA BB CC"

echo "16i C0 p AA p BB p CC p" | dc
192
170
187
204


OR

echo -e "16i\t$x"|sed 's/ / p /g' |sed 's/$/ p/'|dc
192
170
187
204

_____________

Single number conversion

Hex to Integer
echo 16i 57 p |dc
87

Integer to Hex
echo 87 16 o p |dc

57
=====================================================================================================================

superyongzhe 发表于 2010-11-17 21:20:47

不错,mark!!

ssaweee 发表于 2010-11-17 21:34:48

linux shell 比较酷
页: [1]
查看完整版本: linux下怎样把txt文件读成自己想要的格式!