bashtextawkreversetac

Awk - Printing n last, interspersed lines containing keyword


Assume a multi-line text file file, with some lines beginning with the keyword baz.

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

How do I display all those lines not starting with the keyword as well as the n last lines starting with the keyword?

If n=2, the result should look like this:

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

I believe that awk may be the way to go here. Something along the lines of:

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

What do I need to change in my above code to make this work?


Solution

  • You can't manipulate or access your Bash variables from Awk, any more than you can access a variable inside a C program from Bash.

    tac file |
    awk '$1 =="baz" && ++counter<=2 {print; next}
         $1 !="baz"' |
    tac