加班费计算的awk计算

时间:2014-09-28 20:12:53

标签: function unix awk

对于以下数据,我试图确定使用awk文件的总时间。 (加班规则:如果工作超过40小时,每小时工资1.5倍)

Natlie Attired 902-555-1234 10.40 44 
Guy Wyre 401-555-3421 11.75 40

这是我到目前为止所拥有的

BEGIN{
     FS=" "
}
function total(){
    hours = awk {print $5}
    rate = awk {print $4}
    if(hours<=40)
        sum=rate*hours
        return sum
    else
        sum=(hours - 40 * 1.5 * rate) + (rate*hours)
        return sum
}

{
    printf("%s %s worked %d hours, for a total pay of %.2f.\n", $1, $2,$5, total())
}

我需要更改什么才能生成准确的答案?

2 个答案:

答案 0 :(得分:2)

为了让它无误地执行,我不得不:

  • 移除awk {print ...}$5
  • 周围的$4
  • 将大括号添加到if-then-else语句

为了使计算正确,我不得不:

  • 将括号括在hours - 40
  • 附近
  • 1.5替换为0.5(或者将(rate * hours)替换为(rate * 40)

结果代码:

function total() {
    hours = $5;
    rate = $4;
    if (hours <= 40) {
        sum = rate * hours;
        return sum;
    }
    else {
        sum = ((hours - 40) * 0.5 * rate) + (rate * hours);
        return sum;
    }
}

{
    printf("%s %s worked %d hours, for a total pay of %.2f.\n", $1, $2, $5, total());
}

输出:

Natlie Attired worked 44 hours, for a total pay of 478.40.
Guy Wyre worked 40 hours, for a total pay of 470.00.

答案 1 :(得分:2)

$ cat tst.awk
function total(     regHours, otHours, rate, sum){
    rate = $4
    regHours = $5
    if (regHours > 40) {
        otHours = regHours - 40
        regHours = 40
    }
    sum = ((otHours * 1.5) + regHours) * rate
    return sum
}

{
    printf "%s %s worked %d hours, for a total pay of %.2f.\n", $1, $2, $5, total()
}
$
$ awk -f tst.awk file
Natlie Attired worked 44 hours, for a total pay of 478.40.
Guy Wyre worked 40 hours, for a total pay of 470.00.