grep Last n Matches Across Files

2019-03-29 20:48发布

I'm using grep to extract lines across a set of files:

grep somestring *.log

Is it possible to limit the maximum number of matches per file to the last n matches from each file?

标签: shell grep
4条回答
Root(大扎)
2楼-- · 2019-03-29 21:02
for file in /path/to/logs/*.log 
do 
   tail <(grep -H 'pattern' "$file")
done

This will list last 10 matches as tail by default lists last 10 lines. If you wish to get a different number then the following would help -

for file in /path/to/logs/*.log 
do 
   tail -n number <(grep -H 'pattern' "$file")
done

where number can be your number of lines

查看更多
劳资没心,怎么记你
3楼-- · 2019-03-29 21:04

Well I think grep does not support to limit N matches from the end of file so this is what you have to do

ls *.log | while read fn; do grep -iH create "$fn" | tail -1; done

Replace tail -1 -1 with N. (-H options is to print the file name else it wont be printed if you are grep in a single file and thats exactly we are doing above)

NOTE: Above soln will work fine with file names with spaces.

For N matches from the start of the file

grep -i -m1 create *.log

Replace -m1 1 with N.

查看更多
\"骚年 ilove
4楼-- · 2019-03-29 21:15

Kind of off the cuff here, but read this How to do something to every file in a directory using bash? as a starting point. Here's my take, assuming just the last 20 matches from each file.

for i in * 
do
  if test -f "$i" 
  then
    grep somestring $i | tail -n 20
  fi
done

Might not be completely correct, don't have files in front of me to check with, but should be a starting point.

查看更多
Fickle 薄情
5楼-- · 2019-03-29 21:20

Last occurrence of search pattern in every log file under current directory:

find . -name \*log\* | xargs -I{} sh -c "grep --color=always -iH pattern {} | tail -n1"

First occurrence of search pattern in every log file under current directory:

find . -name \*log\* | xargs -I{} sh -c "grep --color=always -iH pattern {} | head -n1"

replace 1 in -n1 with number of occurrences you want


Alternatively you can use find's -exec option instead of xargs

find . -name \*log\* -exec sh -c "grep --color=always -iH pattern {} | tail -n1" \;

You can use -mtime with find to limit down your search of log files to, let's say 5 days

find . -mtime -5 -name \*log\* | xargs -I{} sh -c "grep --color=always -iH pattern {} | tail -n1"

查看更多
登录 后发表回答