zoukankan      html  css  js  c++  java
  • linux系统awk命令求一行值的和、平均值、最大值和最小值

    1、和

    [root@centos7 test]# cat a.txt
    3 8 9 4
    2 4 8 1
    9 8 4 2
    8 5 3 2
    [root@centos7 test]# sed -n '1p' a.txt
    3 8 9 4
    [root@centos7 test]# sed -n '1p' a.txt | awk '{for(i = 1; i <= NF; i++) sum += $i; print sum}'
    24
    [root@centos7 test]# sed -n '2p' a.txt | awk '{for(i = 1; i <= NF; i++) sum += $i; print sum}'
    15
    [root@centos7 test]# sed -n '3p' a.txt | awk '{for(i = 1; i <= NF; i++) sum += $i; print sum}'
    23
    [root@centos7 test]# sed -n '4p' a.txt | awk '{for(i = 1; i <= NF; i++) sum += $i; print sum}'
    18

    2、平均值

    [root@centos7 test]# cat a.txt
    3 8 9 4
    2 4 8 1
    9 8 4 2
    8 5 3 2
    [root@centos7 test]# sed -n '1p' a.txt
    3 8 9 4
    [root@centos7 test]# sed -n '1p' a.txt | awk '{for(i = 1; i <= NF; i++) sum += $i; print sum/NF}'
    6
    [root@centos7 test]# sed -n '2p' a.txt | awk '{for(i = 1; i <= NF; i++) sum += $i; print sum/NF}'
    3.75
    [root@centos7 test]# sed -n '3p' a.txt | awk '{for(i = 1; i <= NF; i++) sum += $i; print sum/NF}'
    5.75
    [root@centos7 test]# sed -n '4p' a.txt | awk '{for(i = 1; i <= NF; i++) sum += $i; print sum/NF}'
    4.5

    3、最大值

    [root@centos7 test]# cat a.txt
    3 8 9 4
    2 4 8 1
    9 8 4 2
    8 5 3 2
    [root@centos7 test]# sed -n '1p' a.txt
    3 8 9 4
    [root@centos7 test]# sed -n '1p' a.txt | awk 'BEGIN{max = 0}{for(i = 1; i <= NF; i++) if($i > max) max = $i;print max}'
    9
    [root@centos7 test]# sed -n '2p' a.txt | awk 'BEGIN{max = 0}{for(i = 1; i <= NF; i++) if($i > max) max = $i;print max}'
    8
    [root@centos7 test]# sed -n '3p' a.txt | awk 'BEGIN{max = 0}{for(i = 1; i <= NF; i++) if($i > max) max = $i;print max}'
    9
    [root@centos7 test]# sed -n '4p' a.txt | awk 'BEGIN{max = 0}{for(i = 1; i <= NF; i++) if($i > max) max = $i;print max}'
    8

    4、最小值

    [root@centos7 test]# cat a.txt
    3 8 9 4
    2 4 8 1
    9 8 4 2
    8 5 3 2
    [root@centos7 test]# sed -n '1p' a.txt
    3 8 9 4
    [root@centos7 test]# sed -n '1p' a.txt | awk 'BEGIN{min = 999999999}{for(i = 1; i <= NF; i++) if($i < min) min = $i; print min}'
    3
    [root@centos7 test]# sed -n '2p' a.txt | awk 'BEGIN{min = 999999999}{for(i = 1; i <= NF; i++) if($i < min) min = $i; print min}'
    1
    [root@centos7 test]# sed -n '3p' a.txt | awk 'BEGIN{min = 999999999}{for(i = 1; i <= NF; i++) if($i < min) min = $i; print min}'
    2
    [root@centos7 test]# sed -n '4p' a.txt | awk 'BEGIN{min = 999999999}{for(i = 1; i <= NF; i++) if($i < min) min = $i; print min}'
    2
  • 相关阅读:
    联赛模拟测试22 D. 简单计算
    联赛模拟测试22 B. 分组配对 倍增+二分
    斜率优化DP总结
    洛谷 P5490 【模板】扫描线
    容斥原理学习笔记
    联赛模拟测试20 C. Weed 线段树
    联赛模拟测试20 B. Walk (建图)
    联赛模拟测试20 A. Simple (数学)
    洛谷 P2617 Dynamic Rankings 树套树
    社区团购模式
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14664686.html
Copyright © 2011-2022 走看看