代码之家  ›  专栏  ›  技术社区  ›  ant

打印匹配行后的所有行

  •  0
  • ant  · 技术社区  · 14 年前

    如何打印第n行匹配模式后的所有行,但忽略匹配行(包括匹配行)前的所有行,下面是一个示例:

    row1 something in this row
    row2 something in this row
    row3 something in this row
    row4 don't need to match the whole line, something like java String.contains()
    row5 something in this row
    row6 something in this row
    row7 something in this row
    row8 something in this row
    row9 something in this row
    row10 something in this row
    

    我想在包含第4行的行之后的任何位置打印该行中的行,是否可以使用awk或sed,或者其他任何方式?

    输出应为:

    row5 something in this row
    row6 something in this row
    row7 something in this row
    row8 something in this row
    row9 something in this row
    row10 something in this row
    

    我也看到过类似的问题:

    Awk - print next record following matched record

    但我不知道如何适应我的需要。

    6 回复  |  直到 12 年前
        1
  •  1
  •   codaddict    14 年前

    如果Perl可以做到:

    perl -ne 'print if($f); $f=1 if(/row4/)'
    

    Code in Action

        2
  •  2
  •   Dennis Williamson    14 年前

    试试这个:

    sed '1,/row4/d' inputfile
    
        3
  •  0
  •   andr    14 年前

    您可以使用以下命令:

    grep -A 5 "row4" test.txt
    

    输出将是:

    row4
    row5
    row6
    row7
    row8
    row9
    

    -A 追求你能用的东西 -B 以前用过的钥匙。 5 是要输出的行数。当然,你可以随心所欲地选择。

        4
  •  0
  •   Paul Rubel    14 年前

    这样一来,古鲁可能会大大缩短它:

    #!/usr/bin/perl
    $pat = shift(@ARGV);
    $p = 0;
    while(<>) {
      if ($p == 1) { print $_;}
      if ($_ =~ /$pat/) {
        $p = 1;
      }
    }
    

    从命令行:

    $ ./p.pl dat4 datafile
    
        5
  •  0
  •   ghostdog74    14 年前
     awk 'c&&c>0;/row4/{c=5}' file
    
        6
  •  0
  •   j0k gauthamp    12 年前
    awk -v pattern="row4" 'go {print} $0 ~ pattern {go = 1}' input_file