Average result of text file

Hi all

I have created a script to allow me to gain a number of file times and how long they take to execute. I have been asked to get the average time for the log. The log will update every 5 minutes and never be empty.

141
152
157
161
168
169
171
179
202
207
229
651
666
714
759
795
823
845
853
863
931
978
982
1005
1063
1064
1071
1079
1107
1132
1150
1174
1212
1243
1303
1336
1378
1475
1591
1673
1697
1723
1729
1730

This is how the numbers are displayed within the text file (in milliseconds) - how do I write a script to add them all together and divide by the number of rows which could change every 5 minutes?

Incase you want too see the script I have created

get_file=`ls -rt localhost_access_log.*.txt|tail -1`
cat $get_file | tail -1000 | grep "objectId" | awk -F 'HTTP/1.1" 200' '{ print $2}'|awk -F' ' '{ print $2 }' | sort -n>/opt/product/apachetomcat/apm/epagent/epaplugins/centrica/correspondence_log_files/9080.txt

min_value=`cat /opt/product/apachetomcat/apm/epagent/epaplugins/centrica/correspondence_log_files/9080.txt|head -1`
max_value=`cat /opt/product/apachetomcat/apm/epagent/epaplugins/centrica/correspondence_log_files/9080.txt|tail -1`

Your entire cat/tail/grep/awk... could be simplified and the avg calculation could incorporated into the pipeline, but as a stand-alone avg calculation given your sample file is:

awk '{s+=$0;fnr=FNR}END {printf("%.2f\n", s/fnr}' myFile

Are you able to explain this code to me not sure I understand it fully?

awk '
# Code inside { } braces without other qualifiers is run once per line
{ 
        # Add the current line, $0, to the total in s.  The +0 guarantees its treated as a number, not a string.
        s+=$0+0
        # Store the current record (line) count inside the fnr variable.  FNR is a special variable meaning file record number.
        fnr=FNR
}
# This code runs once, after myFile has been processed.
END {
        # Print the sum, divided by the number of records, to two decimal places
        printf("%.2f\n", s/fnr)
}' myFile
1 Like