Grep Recent n File Matches

I use grep to extract strings through a set of files:

grep somestring * .log

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

+5
source share
4 answers

Well, I think grep doesn't support limiting N matches from the end of the file, so this is what you need 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, otherwise it will not be printed if you are grep in one file, and this is what we do above)

NOTE. Above soln, it works fine with filenames with spaces.

For N matches from the beginning of the file

grep -i -m1 create *.log

Replace -m11 with N.

+7
source

, - bash? . , 20 .

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

, , , , .

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

10 tail 10 . , -

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

number

+1

:

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

First appearance of the search pattern in each log file in the current directory:

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

replace 1in -n1with the number of occurrences you want


Alternatively you can use find -execinsteadxargs

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

You can use -mtimewith findto limit the search for log files to say 5 days

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

0
source

All Articles