2

在命令行进行简单的统计分析

 3 years ago
source link: https://www.lujun9972.win/blog/2020/08/23/%E5%9C%A8%E5%91%BD%E4%BB%A4%E8%A1%8C%E8%BF%9B%E8%A1%8C%E7%AE%80%E5%8D%95%E7%9A%84%E7%BB%9F%E8%AE%A1%E5%88%86%E6%9E%90/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

使用awk获取最小值、最大值、中位数和平均值

使用awk先把数据存入一个数组中,然后对数组进行排序后就可以自己写代码找出最小值、最大值、中位数和平均值了:

#! /usr/bin/awk -f
{
    sum += $1                   # 假设数据放在第一列
    nums[NR] = $1  # 将数据记录到数组中
}
END {
    if (NR == 0) exit  #防止出现处于0的情况To avoid division by zero

    asort(nums)  #  先对数据进行排序,用于记录中位数

    # 计算中位数
    median = (NR % 2 == 0) ? ( nums[NR / 2] + nums[NR / 2 + 1] ) / 2  : nums[int(NR / 2) + 1]

    # 计算平均
    mean = sum/NR

    printf "min = %s, max = %s, median = %s, mean = %s\n", nums[1], nums[NR], median, mean
}

我们可以实验一下:

seq -10 3 30|~/bin/calculate.awk
min = -10, max = 29, median = 9.5, mean = 9.5

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK