这可以更快地完成(读取文件,替换[sed],写入新文件)

时间:2010-09-12 10:34:23

标签: bash file sed substitution

我在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
系统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
系统10m10.170s


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

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


4 个答案:

答案 0 :(得分:4)

你需要Vim附带的xxd命令。

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

答案 1 :(得分: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}一次。

答案 2 :(得分:2)

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

ruby -ne 'print "#{$_.chomp.gsub(/[0-9A-F]{2}/) { |s| s.to_i(16).chr }}\x00\x00"'

答案 3 :(得分: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()