linux 中输出中位数

 

1、

[root@PC1 test2]# ls
a.txt  b.txt  test.sh
[root@PC1 test2]# cat a.txt    ## 测试数据
8
2
4
8
7
3
[root@PC1 test2]# cat b.txt
8
3
4
8
5
3
6
[root@PC1 test2]# cat test.sh       ## 程序
#!/bin/bash

lines=$(sed -n "$=" $1)
let test=lines%2

if [ $test -eq 0 ]
then
        let line1=lines/2
        let line2=lines/2+1
        sort -n $1 | awk -v a=$line1 -v b=$line2 'NR == a || NR == b {sum += $1} END {print sum/2}'
else
        let line1=lines/2+1
        sort -n $1 | awk -v a=$line1 'NR == a'
fi

[root@PC1 test2]# bash test.sh a.txt    ## 输出a.txt的中位数
5.5
[root@PC1 test2]# bash test.sh b.txt    ## 输出b.txt的中位数
5

 

posted @ 2022-06-01 20:38  小鲨鱼2018  阅读(380)  评论(0编辑  收藏  举报