Grep after and before lines of last Match

10,822

Solution 1

If you like to have all in one command, try this awk

awk '/search/ {f=NR} {a[NR]=$0} END {while(i++<NR) if (i>f-3 && i<f+3) print a[i]}' file

How it works:

awk '
/search/ {                      # Is pattern found
    f=NR}                       # yes, store the line number (it will then store only the last when all is run
    {
    a[NR]=$0}                   # Save all lines in an array "a"
END {
    while(i++<NR)               # Run trough all lines once more
        if (i>f-3 && i<f+3)     # If line number is +/- 2 compare to last found pattern, then 
            print a[i]          # Printe the line from the array "a"
    }' file                     # read the file

A more flexible solution to handle before and after

awk '/fem/ {f=NR} {a[NR]=$0} END {while(i++<NR) if (i>=f-before && i<=f+after) print a[i]}' before=2 after=2 file

Solution 2

Unless I am completely misunderstanding the question, you can just tail the last 21 lines

 grep -A10 -B10  "searchString" my.log | tail -n 21

i.e.

> for i in {1..10}; do echo $i >> example; done; \
echo foo >> example; \
for i in {1..10}; do echo $i >> example; done; \
for i in {A..Z}; do echo $i >> example; done; \
for i in {a..j}; do echo $i >> example; done; \
echo foo >> example; \
for i in {k..z}; do echo $i >> example; done
> grep -A10 -B10  foo example | tail -n 21
a
b
c
d
e
f
g
h
i
j
foo
k
l
m
n
o
p
q
r
s
t

Solution 3

You can try this,

tac yourfile.log | grep -m1 -A2 -B2 'search' | tac
Share:
10,822
RaceBase
Author by

RaceBase

#SOreadytohelp

Updated on June 04, 2022

Comments

  • RaceBase
    RaceBase almost 2 years

    I am searching through few logs and I want to grep the last match along with it's above and below few lines.

    grep -A10 -B10 "searchString" my.log will print all the matches with after and before 10 lines grep "searchString" my.log | tail -n 1 will print the last match.

    I want to combine both and get the after and before 10 lines of last match.