【问题标题】:Why the first line of the command line is not taken for the output为什么命令行的第一行不作为输出
【发布时间】:2020-08-27 13:19:38
【问题描述】:
sed '1d'|awk 'BEGIN{FS=";";sum=0} {sum+=$3; avg=sum/NR; if($3<avg) print $3}'

这是我尝试打印工资低于所有员工平均工资的员工工资的 unix 命令。给出的输入是:

Empid;Empname;Salary
101;V;30000
102;A;45000
103;I;15000
104;S;40000

根据输入,平均工资= 32500,这意味着 30000,15000 都应显示在输出中。但我只能得到 15000 作为我的输出。请帮助并告诉我哪里出错了。

【问题讨论】:

  • 当时您计算的是30000 &lt; avgavg == 30000,而不是32500

标签: linux shell unix awk


【解决方案1】:
awk -F";" 'NR>1 {sum += s[++i] = $3}
    END {avg=sum/length(s); for (i=1;i in s;i++) if (s[i]<avg) print s[i]}' file
30000
15000

此外,无需同时使用sedawk。使用awk 存储所有工资,并在END 部分将它们与平均值进行比较。

【讨论】:

    【解决方案2】:

    您能否根据所示示例尝试以下、编写和测试。将&lt;= 更改为&lt;,以防您只想在这里获得低于平均水平的结果。

    awk '
    BEGIN{
      FS=OFS=";"
    }
    FNR==NR{
      sum+=$NF
      count++
      next
    }
    FNR==1{
      avg=sum/(count-1)
    }
    $NF<=avg
    ' Input_file Input_file
    

    说明:为上述添加详细说明。

    awk '                      ##Starting awk program from here.
    BEGIN{                     ##Starting BEGIN section of this program from here.
      FS=OFS=";"               ##Setting field separator and output field separator as ; here.
    }
    FNR==NR{                   ##Checking condition if FNR==NR which will be TRUE when first time Input_file is being read.
      sum+=$NF                 ##Creating sum which is having last field value keep adding to it.
      count++                  ##Increasing count with 1 here.
      next                     ##next will skip all further statements from here.
    }
    FNR==1{                    ##Checking condition if FNR is 1 the do following.
      avg=sum/(count-1)        ##Creating avg which has division of sum and count-1 here.
    }
    $NF<=avg                   ##Checking condition if last field is lesser than or equal to avg then print that line.
    ' Input_file Input_file    ##Mentioning Input_file names here.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      相关资源
      最近更新 更多