【问题标题】:Omit lines from the beginning or end of a file in Bash [duplicate]在 Bash 中省略文件开头或结尾的行 [重复]
【发布时间】:2014-01-25 23:44:52
【问题描述】:

给定一个文本文件a.txt,如何从文件中截取头部或尾部?

例如,删除前 10 行或后 10 行。

【问题讨论】:

    标签: bash sed awk head tail


    【解决方案1】:

    列出文件的最后 10 行以外的所有行:

    head -n -10 file
    

    列出文件的前 10 行以外的所有行:

    tail -n +10 file
    

    【讨论】:

      【解决方案2】:

      要省略文件开头的行,您可以使用tail。例如,给定一个文件a.txt

      $ cat > a.txt
      one
      two
      three
      four
      five
      ^D
      

      ...您可以从第三行开始,省略前两行,为-n 参数传递一个前面带有+ 的数字:

      $ tail -n +3 a.txt
      three
      four
      five
      

      (或简称tail +3 a.txt。)

      要省略文件末尾的行,您可以对head 执行相同操作,但前提是您拥有 GNU coreutils 版本(例如,Mac OS X 附带的 BSD 版本将无法使用) .要省略文件的最后两行,请为 -n 参数传递一个负数:

      $ head -n -2 a.txt
      one
      two
      three
      

      如果您的系统上没有head 的GNU 版本(并且您无法安装它),您将不得不求助于其他方法,例如@ruifeng 提供的方法。

      【讨论】:

        【解决方案3】:

        要剪切前 10 行,您可以使用其中任何一个

        awk 'NR>10' file
        sed '1,10d' file
        sed -n '11,$p' file
        

        要剪切最后 10 行,可以使用

        tac file  | sed '1,10d' | tac
        

        或使用head

        head -n -10 file
        

        【讨论】:

          【解决方案4】:
          cat a.txt | sed '1,10d' | sed -n -e :a -e '1, 10!{P;N;D;};N;ba'
          

          【讨论】:

          • 你不应该把cat文件给sed,它可以自己读取文件。
          【解决方案5】:
          IFS=$'\n';array=( $(cat file) )
          for((i=0;i<=${#array[@]}-10;i++))  ; do echo "${array[i]}"; done
          

          【讨论】:

          • 不清楚您的代码在做什么。也许你可以把它分成更多的行并解释答案如何适用于问题。
          猜你喜欢
          • 2020-05-04
          • 2016-03-08
          • 2022-12-02
          • 1970-01-01
          • 2014-03-14
          • 1970-01-01
          • 1970-01-01
          • 2015-12-11
          • 2016-05-27
          相关资源
          最近更新 更多