3

How do I write a awk script that scans the input file for "start" and finds the line containing "next" and displays the following line? Something like this:

    [user]$ cat test.txt
    start
    next
    This line should print
    Ignore this


    [user]$ display.awk test.txt
    This line should print

    [user]$ cat test1.txt
    Ignore this
    next
    Ignore this
    start
    Ignore this
    next
    This line should print
    Ignore this
    next
    Too late so ignore this too
    start
    Ignore this too

    [user]$ display.awk test1.txt
    This line should print
0

3 Answers 3

5

Here is a one-liner:

awk 'BEGIN {start="no"; nextline="no"}; nextline=="yes" {print; exit}; (start=="yes" && /^next$/) {nextline="yes"}; /^start$/ {start="yes"}' test.txt 

And as a standalone script:

#!/bin/awk -f

BEGIN {start="no"; nextline="no"}
nextline=="yes" {print; exit}
(start=="yes" && /^next$/) {nextline="yes"}
/^start$/ {start="yes"}

Explanation

This might make more sense reading the first dot point first, then reading the rest in reverse.

  • BEGIN {start="no"; nextline="no"}: to start, set both variables to "no" (i.e. we haven't found them yet). N.B. next is a reserved word, so I used nextline.
  • nextline=="yes" {print; exit}: when we have found next from a previous line, print the line then exit.
  • (start=="yes" && /^next$/) {nextline="yes"}: after finding the start, if we also find next in a line, then set nextline to "yes"
  • /^start$/ {start="yes"}: if we find start, set start to "yes".
1
  • 1
    Yes, exactly. Replace /^start$/ with /^Start from here$/ Commented Oct 28, 2015 at 6:47
4

Alternative solution with sed:

sed -n '/start/,${        # in this range
$!{                       # if not the last line                         
/next/{                   # and if line matches "next"
n                         # read in the next line
p                         # print pattern space
q                         # quit
}
}
}' infile

With gnu sed:

sed -n '/start/,${$!{/next/{n;p;q}}}' infile
0
1

this should also work

awk 'BEGIN {l1=0} /^start$/{l1=1} /^next$/ && l1==1 {l2=NR+1} NR==l2 {print;l1=0}' test.txt

it uses the record number NR to print the record after the first next encountered after a start line.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.