1

I have a log file that exists in multiple directories one for each client. I am trying to run the following:

find . -iname "20140926.log" -exec cat {} \; | grep 123456 | grep 'food="100"' | wc -l

this returns me the result I want but I want to know for each fullpath what the individual count was. For example I tried this:

for f in "/path/*"; do
  result=`eval grep 123456 "$f/logs/20140926.log" | grep 'food="100"' | wc -l`
  echo "$f - $result" 
done

But it just returning a list of all my directories and then the final result. I am expecting something like this:

/path1/log/file.log - 0
/path2/log/file.log - 2
/path3/log/file.log - 39
etc...

This way I can see the wc for my grep for each path/file

1

grep -H will print file names for you, but since you're doing multiple greps you can just echo the file name yourself:

for f in $(find . -name '20140926.log'); do
    echo -n "$f "
    grep 123456 $f | grep -c 'food="100"'   # grep -c prints count of matches
done
  • This will break on even a simple space, let alone harder things. Using a for loop to iterate over arbitrary text is never a good idea. – terdon Sep 27 '14 at 3:37
0

You could do

find . -name 20140926.log | while read file; do 
    printf "%s - " "$file "; grep 123456 $file | grep -c 'food=100' 
done

This has the advantage of not breaking on file names with spaces. It does break on newlines and backslashes, however. If your files can be completely unreasonable, use this:

find . -name 20140926.log | while read -rd '' file; do 
    printf "%s - " "$file "; grep 123456 "$file" | grep -c 'food=100'      
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.