【问题标题】:Displaying selected lines using head and tail command使用 head 和 tail 命令显示选定的行
【发布时间】:2021-01-30 04:49:11
【问题描述】:

如何使用带有管道的“head”和“tail”命令仅显示我选择的文件“imaginaryfile”(有 10 行)中的第 2 行和第 3 行?

到目前为止我已经尝试过:

>$ head -n  3 imaginaryfile | tail -n 2 > > (head -n 1) > > (tail -n 1)

第 3 行的输出来了,但我没有得到第 2 行的输出。我该怎么做才能纠正这个问题并得到第 2 行和第 3 行的输出?

【问题讨论】:

  • 我只使用一个 sed 调用:sed -n '2,3p; 3q' imaginaryfile
  • 这将有助于未来的读者查看问题中的测试文件内容和所需的输出。要使用 tail 和 head 从 10 行测试文件中获取第 2 行和第 3 行,您可以 tail -n +2 testfile | head -n2

标签: bash unix command-line


【解决方案1】:
head -3 file | tail -n +2

head 将打印前 3 行。此输出将作为 tail 命令的输入,该命令将从第二行开始打印到末尾。

来自man tail

-n, --lines=[+]NUM 输出最后 NUM 行,而不是最后 10 行;或使用 -n +NUM 以输出开头 第 NUM 行

【讨论】:

    【解决方案2】:

    您可以通过简单的awk 做到这一点。

    awk '
    FNR>=2 && FNR<=3{
      print
      if(FNR==3){
        exit
      }
    }
    ' Input_file
    


    awk 中的变量中给出范围,从您要打印的位置到您要打印的位置。

    awk -v from="2" -v till="3" '
    FNR>=from && FNR<=till{
      print
      if(FNR==till){
        exit
      }
    }
    ' Input_file
    

    【讨论】:

      【解决方案3】:

      要打印选定的行,请使用以下任何 Perl 单行:

      # Explicit and simple code:
      perl -ne 'print if $. >= 2 && $. <= 3' input_file
      
      # Shorter, but less explicit code:
      perl -ne 'print if 2..3' input_file
      
      # Longer and more complex code, but runs faster for larger files, 
      # because the script exits after line 3:
      perl -ne 'next if $. < 2; last if $. > 3; print;' input_file
      

      例子:

      seq 1 10 | perl -ne 'print if $. >= 2 && $. <= 3'
      2
      3
      

      Perl 单行代码使用这些命令行标志:
      -e:告诉 Perl 查找内联代码,而不是在文件中。
      -n:循环输入一行一次,默认分配给$_

      $.:当前输入行号。

      另请参阅:
      perldoc perlrun: how to execute the Perl interpreter: command line switches
      perldoc perlvar: Perl predefined variables

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-19
        • 1970-01-01
        • 2010-12-30
        • 1970-01-01
        • 2013-06-29
        • 1970-01-01
        相关资源
        最近更新 更多