代码之家  ›  专栏  ›  技术社区  ›  Michael Gruenstaeudl

awk-最后打印n行,包含关键字的分散行

  •  0
  • Michael Gruenstaeudl  · 技术社区  · 7 年前

    假设一个多行文本文件 file ,一些行以关键字开头 baz .

    $ cat file
    foo bar
    baz qux   # line to be deleted
    foo bar
    foo bar baz
    baz
    baz qux quux
    foo bar
    

    如何显示不以关键字开头的所有行以及 n 最后一行以关键字开头?

    如果 n=2 ,结果应如下所示:

    $ sought_command file
    foo bar
    foo bar
    foo bar baz
    baz
    baz qux quux
    foo bar
    

    我相信 AWK 可能是到这里的路。沿着这条线的东西:

    counter=1
    tac file | awk '{
    if ($1 =="baz" && counter<=2)
        {print $0; counter=$((counter+1));}
    else if ($1 =="baz" && counter>2)
        {next;}
    else
        {print $0;}
    }' | tac
    

    我需要在上面的代码中更改什么才能使其工作?

    3 回复  |  直到 7 年前
        1
  •  1
  •   tripleee    7 年前

    tac file |
    awk '$1 =="baz" && ++counter<=2 {print; next}
         $1 !="baz"' |
    tac
    
        2
  •  0
  •   Ed Morton    7 年前
    $ tac file | awk '$1!="baz" || c++<2' | tac
    foo bar
    foo bar
    foo bar baz
    baz
    baz qux quux
    foo bar
    
        3
  •  0
  •   stack0114106    7 年前

    $ cat michael.txt
    foo bar
    baz qux   # line to be deleted
    foo bar
    foo bar baz
    baz
    baz qux quux
    foo bar
    $ perl -0777 -ne ' $x++ for(/^baz/gm); $y=$x-2; while( $y-- ) { s/^baz.+?\n//m } ; print ' michael.txt
    foo bar
    foo bar
    foo bar baz
    baz
    baz qux quux
    foo bar
    $