search - Grep after and before lines of last Match -


i searching through few logs , want grep last match along it's above , below few lines.

grep -a10 -b10 "searchstring" my.log print matches after , before 10 lines grep "searchstring" my.log | tail -n 1 print last match.

i want combine both , after , before 10 lines of last match.

if have in 1 command, try awk

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

how works:

awk ' /search/ {                      # pattern found     f=nr}                       # yes, store line number (it store last when run     {     a[nr]=$0}                   # save lines in array "a" end {     while(i++<nr)               # run trough lines once more         if (i>f-3 && i<f+3)     # if line number +/- 2 compare last found pattern,              print a[i]          # printe line array "a"     }' file                     # read file 

a more flexible solution handle before , 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 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -