Grep after and before lines of last Match

廉价感情. 提交于 2019-12-22 08:37:07

问题


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.


回答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



回答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



回答3:


You can try this,

tac yourfile.log | grep -m1 -A2 -B2 'search' | tac


来源:https://stackoverflow.com/questions/24422683/grep-after-and-before-lines-of-last-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!