I am trying to calculate what is the % of successful queries in apache log. I have two commands:

cat access_log|cut -d' ' -f10|grep "2.."|wc -l


cat access_log|cut -d' ' -f10|wc -l

They return me the number of successful queries and total queries number. I want to calculate what is the % of successful requests using bash and if it is possible - it should be 1 line script. It suppose to output just the % number like - 50 or 12 without any additional info.

I tried to use bc with it but failed because of lack of knowledges. Can somebody help me?


Try this:

echo $(( 100 * $( cut -d' ' -f10 access_log|grep "2.."|wc -l) / $(cut -d' ' -f10 access_log|wc -l) ))

Bash can only handle integers.


Using awk and only iterates through the logfile once:

awk '{if ((199 < $9) && ($9 < 300)) {SUMOK++} else {OTHER++}} END { printf "%d\n", ((SUMOK/NR)*100)}' access_log

You can try this. Replace $9 with correct field number of status code.

awk '{if ($9 == 200)  no_of_200+=1 } END{ perc=(no_of_200/NR)*100; print perc}' access.log
sed -ne'\|^\([^ ]*  *\)\{9\}2..|=;$=;$s|.*|2ksmzlm/p|'|dc


for example:

printf %s\\n 1 2 3 4 5 6 7 8 9 10 |
sed -ne'/1/=;$=;$s|.*|2ksmzlm/p|p'|dc


...to show that sed matched the 1 pattern against 20% of its input lines.

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.