linux - 如何在 bash shell 脚本中计算文件中每一行的中位数

标签 linux bash shell

我正在尝试从我的 bash shell 脚本中的文件中计算每一行的中值。我相信有一种方法可以通过使用 cut、sort、head 和 tail 的流水线命令来实现这一点,但我不知道如何将这个过程集成到我现有的代码中。我想在计算平均值的同一点计算中位数。执行此操作的最佳方法是什么?

while read i
do
    sum=0
    count=0
    mean=0
    median=0
    for num in $i
    do
        sum=$(($sum + $num))
        count=`expr $count + 1`
        mean=`expr $sum / $count`
        #Need to calculate the median
    done
    echo "Sum: $sum Mean: $mean"
done < $2

最佳答案

假设行的长度是可变的:

  1. 使用 bashdatamash :

    while read x
    do    tr -s '\t' '\n' <<< "$x" | \
          datamash  median 1
    done < file
    
  2. 使用 numaverage :

    while read x
    do    tr -s '\t' '\n' <<< "$x" | \
          numaverage -M
    done < file
    

关于linux - 如何在 bash shell 脚本中计算文件中每一行的中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43554862/

相关文章:

linux - 在每行末尾添加变量

windows - Samba 共享权限问题 - 仅具有文件系统权限的公共(public)共享

windows - 将 PowerShell 转换为 Bash

linux - 如何在 Linux shell 脚本中声明?

reactjs - 如何使用 HTTPS 启动 React 项目

linux - 链接到特定的 inode

python - Theano 属性错误: 'module' object has no attribute 'relu'

python - 如何知道正在运行的脚本是否死亡?

linux - 在文件的每一行前面打印文件名

bash shell 脚本 : How to group argument list into N items?