2

我在 bash 脚本中使用这段代码来读取包含多个十六进制字符串的文件,进行一些替换,然后将其写入新文件。大约 300 Mb 大约需要 30 分钟。
我想知道这是否可以更快地完成?

sed 's,[0-9A-Z]\{2\},\\\\x&,g' ${in_file} | while read line; do
 printf "%b" ${line} >> ${out_file}
 printf '\000\000' >> ${out_file}
done

更新:

我做了一些测试,得到了以下结果:

获胜者是:


sed 's,[0-9A-Z]\{2\},\\\\x&,g' ${in_file} | while read line; do
    printf "%b" ${line} >> ${out_file}
    printf '\000\000' >> ${out_file}
done

实际 44m27.021s
用户 29m17.640s
sys 15m1.070s


sed 's,[0-9A-Z]\{2\},\\\\x&,g' ${in_file} | while read line; do
    printf '%b\000\000' ${line} 
done >> ${out_file}

真正的 18m50.288s
用户 8m46.400s
sys 10m10.170s


export LANG=C
sed 's/$/0000/' ${in_file} | xxd -r -ps >> ${out_file}

真实 0m31.528s
用户 0m1.850s
系统 0m29.450s


4

4 回答 4

4

你需要 Vim 自带的 xxd 命令。

export LANG=C
sed 's/$/0000/' ${in_file} | xxd -r -ps > ${out_file}
于 2010-09-12T11:12:08.673 回答
3

由于 bash 中的循环,这很慢。如果您可以让 sed/awk/perl/etc 执行循环,它会快得多。不过,我看不出你如何在 sed 或 awk 中做到这一点。perl 可能很容易,但我不知道足够的 perl 来为你回答这个问题。

至少,你应该能够通过重构你必须做的事情来节省一点时间:

sed 's,[0-9A-Z]\{2\},\\\\x&,g' ${in_file} | while read line; do
 printf '%b\000\000' ${line} 
done >> ${out_file}

至少这样,您每次迭代运行一次 printf 并且仅打开/关闭 ${out_file} 一次。

于 2010-09-12T10:53:12.477 回答
2

切换到完整的编程语言?这是一个 Ruby 单线:

ruby -ne 'print "#{$_.chomp.gsub(/[0-9A-F]{2}/) { |s| s.to_i(16).chr }}\x00\x00"'
于 2010-09-12T10:56:27.743 回答
0

如果你有 Python 并且假设数据很简单

$ cat file
99
AB

脚本:

o=open("outfile","w")
for line in open("file"):
    s=chr(int(line.rstrip(),16))+chr(000)+chr(000)
    o.write(s)
o.close()
于 2010-09-12T11:28:39.133 回答