Reputation: 4257
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?
Upvotes: 6
Views: 12917
Reputation: 8457
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"
Upvotes: 0
Reputation: 9590
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.
Upvotes: 8
Reputation: 77095
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
Upvotes: 1
Reputation: 1047
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.
Upvotes: 1