Awk - Printing n last, interspersed lines containing keyword

awk regex
awk print column matching pattern
awk '(gsub)
awk pattern matching if condition
awk print only matching pattern
awk tutorial
awk examples
awk print line if column matches

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?

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

bash - Awk, 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  Checkout the printing section on the AWK user guide for more information on this. Now we’ve selected a couple of columns to print out, let’s use AWK to search for a specific thing – a number we know exists in the dataset. Note that if you specify what fields to print out, AWK will print the whole line that matches the search by default.

$ tac file | awk '$1!="baz" || c++<2' | tac
foo bar
foo bar
foo bar baz
baz
baz qux quux
foo bar

The GNU Awk User's Guide, 5.4 Controlling Numeric Output with print Next: Printf Examples, Previous: Control Letters, printf "%s %s\n", "don't", "panic" printf "%2$s %1$s\n", "panic", "​don't" a series of rules and function definitions interspersed. If the else keyword appears on the same line as  -f file To specify a file that contains awk script.-v var=value To declare a variable. We will see how to process files and print results using awk. Read AWK Scripts. To define an awk script, use braces surrounded by single quotation marks like this: $ awk '{print "Welcome to awk command tutorial "}'

If you want to try Perl, here is a standalone solution.

$ 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
$

The AWK Programming Language – Nextjournal, awk '{ printf("total pay for %s is $%.2f\n", $1, $2 * $3) }' emp.data This program prints all lines that contain Susie anywhere: matches before the first line of the first input file is read, and END matches after the last line of the last file has been processed. For convenience, we'll treat each field as a word. Is there a way to combine both steps into one command? I'm thinking piping the line number and the filename into sed and printing the line. I'm having a problem with the order in which the grep output is generated. Q1b. Same as above but also print the 2 lines before and 2 lines after the line containing the string (total of 5 lines)?

Matching Patterns and Processing Information with awk, Programming Support Tools: DIGITAL UNIX Versio n 4.0D. This chapter describes the awk command, a tool with the ability to match lines of text in For each matching record, it will print two lines, first the number of the record on n syntax combined with the built-in variable NF to test the value of the last field of a record. The following awk command will read data from employee.txt file line by line and print the first filed after formatting. Here, “ %10s\n ” means that the output will be 10 characters long. If the value of the output is less than 10 characters then the spaces will be added at the front of the value.

Using awk, The first field goes from the beginning of the line up to the delimiter character (​here, This time a command is piped into awk whereas the last time awk was given a This instructs awk to print a newline (\n) so that the header won't display right headers with the columns and interspersed throughout are the heading titles,  RE: Awk only printing lines I'm changing p5wizard (IS/IT--Management) 22 Feb 10 13:54 because of the /CALL VVD/ condition before your program block, that block is only executed for the FORTRAN lines containing that search string

20 awk examples – Linux Hint, Here, “%10s\n” means that the output will be 10 characters long. The default word or field separator for splitting any text is white space. awk command NR variable contains the line number of the file when awk command parses the file. The following awk commands will print the last part and full part of the last column  I want to print all lines from file until the match word please advice how to do that with awk. for example. I want to print all lines until word PPP. remark the first line chuld be diff from AAA ( any word ) cat file.txt AAA ( the first line/word chuld be any word !!!!! ) BBB JJJ OOO 345 211 BBB OOO OOO PPP MMM ((( &&& so I need to get this

Comments
  • How would this logic work? the last few lines still start with baz? Is it possible are you referring to one half and the other half
  • Awk has no idea that there is a Bash variable also named counter.
  • @Inian The output is supposed to contain exactly two lines starting with the keyword, namely the last two baz-starting lines of the input.
  • Thanks for pointing out that awk cannot read shell variables. That being said, your suggested code does not print only the last n lines starting with the keyword. Instead, it duplicates the last line starting with the keyword. Can you revise it?
  • Sorry about that, removed the offending line break. This is really just a refactoring of your script so I was too lazy to actually test.