我正在搜索几个日志,我想在最后一场比赛中上面和下面的几行进行比赛。
grep -A10 -B10 "searchString" my.log
将在10行之后和之前打印所有匹配
grep "searchString" my.log | tail -n 1
将打印最后一场比赛。
我希望将两者结合起来并获得最后一场比赛的10行之前和之后。
答案 0 :(得分:4)
如果您想将所有命令都放在一个命令中,请尝试使用此awk
awk '/search/ {f=NR} {a[NR]=$0} END {while(i++<NR) if (i>f-3 && i<f+3) print a[i]}' file
工作原理:
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
处理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
答案 1 :(得分:3)
除非我完全误解了这个问题,否则你可以tail
过去21行
grep -A10 -B10 "searchString" my.log | tail -n 21
即
> 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
答案 2 :(得分:1)
你可以试试这个,
tac yourfile.log | grep -m1 -A2 -B2 'search' | tac