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
  • 相关阅读:
    hdu 1214 圆桌会议(规律)
    hdu 1280 前m大的数
    hdu 2114 Calculate S(n)
    hdu 1210 Eddy's 洗牌问题
    hdu 1423 Greatest Common Increasing Subsequence(最长公共递增子序列lcis)
    7.30前端之Html简介
    8.3前端之Html列表
    7.30前端之Html头部
    7.30前端之Html元素
    7.23Java之递归练习
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14664686.html
Copyright © 2011-2022 走看看