Search code examples
searchgrepmatchtail

Grep after and before lines of last Match


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.


Solution

  • 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