【问题标题】:unix- show the second line of the fileunix-显示文件的第二行
【发布时间】:2012-12-12 12:49:08
【问题描述】:

此命令显示文件的第二行:

cat myfile | head -2 | tail -1

我的文件包含以下数据:

hello
mark
this is the head line
this is the first line 
this is the second line 
this is the last line

上面的命令将数据打印为:mark

但我无法理解这一点,因为 head -2 用于打印前两行,tail -1 打印最后一行,但如何打印第二行!!???

【问题讨论】:

  • tail 只对 head 的输出进行操作,tail -1 表示打印接收到的最后一行输出。在这种情况下(在管道中),tail 不知道 myfile 存在。您的管道正在按设计工作,您观察到的内容被视为一项功能! ;-)。祝你好运。

标签: unix


【解决方案1】:

您也可以使用“sed”或“awk”来打印特定的行:

示例:

sed -n '2p' myfile

PS: 至于“我的 'head|tail' 有什么问题”命令 - shelltel 是正确的。

【讨论】:

  • 很好。为了提高大文件的效率,我建议'2p;3q'2{p;q;} 或类似的。
【解决方案2】:

tail显示head输出的最后一行,head输出的最后一行是文件的第二行。

头部输出(尾部输入):

hello
mark

尾部输出:

mark

【讨论】:

    【解决方案3】:

    如果您将操作分解为单独的命令,那么它的工作方式将变得显而易见。

    head -2 创建一个包含两行的文件。

    linux> head -2 /tmp/x > /tmp/xx
    linux> cat /tmp/xx  
    hello
    mark
    

    tail -1 打印出文件的最后一行。

    linux> tail -1 /tmp/xx
    mark
    

    【讨论】:

      猜你喜欢
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2018-06-28
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      相关资源
      最近更新 更多