Question

How can we Find the last occurrence a search string (Regex) and then print the next line following it? Assume a Textfile which has Data as below

1 absc
1 sandka
file hjk
2 asdaps
2 amsdapm
file abc

So, from this file, I have to grep or awk the last occurrence of the 2 and print the line that follows it.

Was it helpful?

Solution

awk is always handy for these cases:

$ awk '/2/ {p=1; next} p{a=$0; p=0} END{print a}' file
file abc

Explanation

  • /2/ {p=1; next} when 2 appears in the line, activate the p flag and skip the line.
  • p{a=$0; p=0} when the p flag is active, store the line and unactivate p.
  • END{print a} print the stored value, which happens to be the last one because a is always overwritten.

OTHER TIPS

Using grep

  • grep -A 1 '^2' option displays lines that match 2 at the beginning of the line plus one following line

  • then use tail -1 to print the final line:

grep -A 1 '^2' yourfile | tail -1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top