【问题标题】:Can this be done faster (read file, substitute [sed], write new file)这可以更快地完成吗(读取文件,替换 [sed],写入新文件)
【发布时间】:2010-09-12 10:34:23
【问题描述】:

我在我的 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
sys 0m29.450s


【问题讨论】:

  • 显示输入文件的示例和输出格式
  • 在调用它之前运行它以更改为快速 C 语言环境:export LANG=C
  • @LatinSuD。不知道你的意思。

标签: bash file sed substitution


【解决方案1】:

你需要 Vim 自带的 xxd 命令。

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

【讨论】:

  • +1:我从没想过xxd可以反着用!
【解决方案2】:

由于 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}。

【讨论】:

  • +1 指出多次重定向到同一个文件比一个慢(阅读:有常识)。
  • 你的意思是它应该是 printf '%b${line}\000\000' 因为 '\000\000' 变成了 printf "%b" ${line}
  • @Robertico:不,我是这么写的。 '%b\000\000' 是格式字符串,${line} 是 %b 使用的参数。
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

    如果你有 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 2017-02-15
      相关资源
      最近更新 更多