여러 숫자의 평균 - 쉘 스크립트

여러 숫자의 평균 - 쉘 스크립트

특정 양의 밀리초/초 동안 로그 파일과 grep을 보는 스크립트를 만들었습니다. 최소값과 최대값을 볼 수 있는 항목을 만들었지만 목록의 평균을 찾아야 합니다.

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

최소값:

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

최대_값:

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

목록의 아이디어:

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

평균을 구하는 방법?

답변1

파일의 유일한 항목이 숫자인 경우 단일 awk 명령을 사용하여 모든 것을 얻을 수 있습니다.

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_

다양한 부분을 보실 수 있도록 나누어 봤습니다.

BEGIN은 사용할 모든 변수를 초기화하는 것입니다. 변수 themin은 파일의 어떤 값보다 크면 원하는 대로 큰 값으로 설정할 수 있습니다.

중간 부분은 각 줄과 해당 줄의 각 필드를 반복합니다. 숫자를 합산하고 모든 숫자의 수를 계산하여 마지막에 간단한 나눗셈을 수행할 수 있습니다. 두 개의 if 문은 최소값과 최대값을 수집합니다.

END는 최소, 최대 및 평균을 포함하여 관련 정보를 모두 인쇄합니다.

도움이 되었기를 바랍니다.

답변2

이미 훌륭한 솔루션이 있는 문제에 대해 자신만의 솔루션을 작성할 필요가 없습니다. 결국 당신은 StackOverflow가 아닌 ​​SuperUser에게 요청했습니다.

예를 들어 GNU를 사용하십시오.datamash

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

또는 패키지의 도구를 사용하십시오num-utils

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

관련 정보