0

I have created a script which views a logfile and greps for a specific amount of milliseconds / seconds. I have created something which views the minimum and maximum value however I need to find the average of the list.

logdir_8080='/opt/product/apachetomcat/8.5.5_8080/logs'
cd "$logdir_8080"

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/8080.txt

min_value:

cat /opt/product/apachetomcat/apm/epagent/epaplugins/centrica/correspondence_log_files/8080.txt|head -1

max_value:

cat /opt/product/apachetomcat/apm/epagent/epaplugins/centrica/correspondence_log_files/8080.txt|tail -1

Idea of the list:

233
249
283
283
302
303
332
333
643
851
965
965
972
1022
1135
1182
1213
1232
1264
1273
1390
1403
1414
1429
1474
1537
1540
1543
1545
1556
1565
1566
1577
1589
1591
1599
1602
1621
1622
1647
1653
1705
1740
1772
1774
1933
1935
1983
1990

How to get the average?

1

If the only thing in your file are numbers, you can use a single awk command to get everything.

awk 'BEGIN {themin=10000000; themax=0; thecount=0; thesum=0}
    {for (i=1; i<=NF; i++) {
        thesum += $i;
        thecount++;
        if ($i < themin) {themin = $i}
        if ($i > themax) {themax = $i}
    }}
    END {
      printf("The min is %d\nThe max is %d\nThe sum is %d\nThe total number of items is %d\nThe average of those items is %d\n", themin, themax, thesum, thecount, int(thesum/thecount))
}' _file_

I broke it out so you can see the different sections.

The BEGIN is just initializing all the variables to be used. The variable, themin, can be set to whatever large value you want, as long as it is larger than anything in your file.

The middle part just loops through each line, and each field in that line. It is summing up the numbers, and getting a count of all of the numbers so a simple division can be done at the end. The two if statements collect your min and max values.

The END prints out all of the relevant pieces of information, including your min, max and average.

Hope this helps.

0

No need to write your own solutions for problems that already have splendid solutions. After all, you asked on SuperUser and not on StackOverflow.

For instance use GNU datamash

$ datamash min 1 max 1 mean 1 < yourFile
233     1990    1272.0408163265

or use the tools from the package num-utils

$ numbound -l yourFile
233
$ numbound yourFile
1990
$ numaverage yourFile
1272.04081632653

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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