【问题标题】:Which of two is better in file manipulation?两者中哪一个在文件操作方面更好?
【发布时间】:2013-03-09 04:08:53
【问题描述】:

我有一个包含大量数值 (+2M) 的文件“tbook1”。我必须在 bash (Solaris / RHEL) 中执行以下操作:

Do following:
Remove 1st and last 2 lines
Remove (,") & (")
Substitute (, ) with (,)

我可以使用两种方法:

Method1:
sed -e 1d -e 's/,"//g' -e 's/, /,/g' -e 's/"//g' -e 'N;$!P;$!D;$d' tbook1 > tbook1.3

method2:
tail -n +2 tbook1 | head -n -2 > tbook1.1
sed -e 's/,"//' -e 's/, //' tbook 1.1 > tbook1.2

我想知道哪个更好,即更快更高效(资源使用)?

【问题讨论】:

  • 你能更新文件吗?
  • 不..我不能就地做...我必须保持原来的'tbook'完好无损!

标签: bash shell sed tail head


【解决方案1】:

方法 1 通常会更有效,主要是因为方法 2 的额外管道和读取和写入的中间文件..

【讨论】:

    【解决方案2】:

    方法一仅扫描文件一次并写入1个结果(但请将结果存储在不同名称的文件中) 方法二 2 扫描原始文件和中间结果,写入中间和最终结果。它肯定会慢两倍左右。

    【讨论】:

      【解决方案3】:

      我认为head 和tail 比纯粹的sed 更有效地完成这个线消除任务。但是另外两个答案也是对的。您应该避免运行多次。

      您可以通过将它们链接在一起来改进第二种方法:

      tail -n +2 book.txt | head -n -2 | sed -e 's/,"//' -e 's/, //'
      

      然后head 和tail 更快。自己尝试(在合理大小的文件上):

      #!/usr/bin/env bash
      
      target=/dev/null
      
      test(){
              mode=$1
              start=$(date +%s)
              if   [ $mode == 1 ]; then
                      sed -e 1d -e 's/,"//g' -e 's/, /,/g' -e 's/"//g' -e 'N;$!P;$!D;$d' book.txt > $target
              elif [ $mode == 2 ]; then
                      tail -n +2 book.txt | head -n -2 | sed -e 's/,"//' -e 's/, //' > $target
              else
                      cat book.txt > /dev/null
              fi
      
              ((time = $(date +%s) - $start))
              echo $time "seconds"
      }
      
      echo "cat > /dev/null"
      test 0
      
      echo "sed > $target"
      test 1
      
      echo "tail/head > $target"
      test 2
      

      我的结果:

      cat > /dev/null
      0 seconds
      
      sed > /dev/null
      5 seconds
      
      tail/head > /dev/null
      3 seconds
      

      【讨论】:

      • 感谢尤文,看来我有一个高性能服务器... :) !我对文件(相当大)进行了上述测试,结果如下: [root@cntosmhvtl2 prod]# ./perftest.sh cat > /dev/null 0 seconds sed > /dev/null 0 seconds tail/head > /dev/null 0 秒 [root@cntosmhvtl2 prod]# wc book.csv 4230 71288 1244096 book.csv
      • 我想我会坚持使用 sed 版本...似乎 Solaris 服务器不支持尾部 |头部组合!!
      • 是的,head 的 POSIX 版本不接受-n 之后的负数。 @马科斯
      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 2013-03-24
      相关资源
      最近更新 更多