【问题标题】:Copying last n lines to a new file and then removing the n lines from original将最后 n 行复制到新文件,然后从原始文件中删除 n 行
【发布时间】:2018-05-14 12:31:55
【问题描述】:

所以我有一个文件,我想将最后 3000 行移动到另一个不同的文件,然后从原始文件创建一个没有最后 3000 行的新文件。

我使用的是Mac,我使用的命令如下:

tail -n 3000 fer2017-testing-reduced.arff >> fer2017-training-reduced-3000-more-instances.arff; head -n -3000 fer2017-testing-reduced.arff > fer2017-testing-reduced-3000-less-instances.arff

但是当我运行它时,我得到了错误:

head: illegal line count -- -3000

我不确定我哪里出错了,或者这可能是一个 mac 问题?

【问题讨论】:

    标签: linux bash macos shell


    【解决方案1】:

    并非所有版本的head 都支持负行数。 macOS 上安装的默认设置没有。

    如果你安装了coreutils(如果你安装了Homebrew,你可以这样做:brew install coreutils)你应该可以使用ghead -n -3000

    【讨论】:

      【解决方案2】:

      如果允许使用其他工具,也许可以选择sed

      sed -n '3000,${p}' file > filenew # print lines 3000 to end to new file
      sed -i '3000,${d}' file # Use inplace edit to delete lines 3000 to end from orig.
      

      这里的优点是 $ 自动匹配最后一行。

      【讨论】:

        【解决方案3】:

        阅读更多关于为什么POSIX head and tail not feature equivalent 的信息,head 的 POSIX 版本接受 -n 选项的负整数。

        引自POSIX head 命令文档,

        -n number 每个输入文件的前几行应复制到标准输出。 应用程序应确保数字选项参数是十进制正整数。

        您最好将head -n -3000 更改为tail -n +3001 以从行3000 开始到文件末尾。或者使用 GNU 支持的 head 命令,该命令在 Mac 上作为 GNU coreutils 的一部分提供。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-20
          • 2017-07-16
          • 1970-01-01
          • 2012-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多