awkgreptac

How can i grep the last group of lines using awk?


I have the following contents in my file file.txt

Start
1
2
3
5
end
Start
a
b
c
d
end

How do i use only awk to get the section which is at the end from "start" to "end" as follows?

Start
a
b
c
d
end

Tried efforts:

awk '/Start/ {{ f = 1;n++ }} f && n == 2; /end/ {{ f = 0 }}' file.txt

Solution

  • With tac + awk solution, could you please try following.

    tac Input_file | awk '/^end/{found=1} found; /^Start/{exit}' | tac
    

    Explanation: tac will print Input_file in reverse order(from bottom to up manner), then passing its output to awk command and in awk code printing from first occurrence of end to till first occurrence of start. Exiting from awk code when first occurrence of start is found, again this output is being send to tac which will reverse the output and post it in original form of Input_file.


    2nd solution: Using GNU awk one could try like but it assumes that there is NO discrepancy(means after each start there is end keyword present in OP's Input_file else it will give false positive results) in start and end keywords appearance.

    awk -v RS= '{sub(/.*Start/,"Start")} 1' Input_file