使用awk根据类型列出报告

时间:2013-11-02 16:08:43

标签: bash shell ubuntu awk

我正在尝试使用awk来执行工资单报告,但我不太确定该怎么做。尝试了以下但似乎没有正常工作。我被困了,因为我写的代码设法整理了“薪水”,但仍然列出了其他数据,而不仅仅是姓名和支付。

编辑:我已经尝试了计算部分..但不知道它是如何工作的

需要将结果显示为:

1)整理“薪水”类型,每小时和委托

例如:

Salaried:
Frank    $2333
Mary     $1111

Total salary: $3444
----------------------
Grand Total: $3444

代码:

 echo "***** payroll report ****"
 awk -F',' '{print $2}' | grep "Salaried" $PAYROLL

 totalcost=0
   salariedcost=0
   for i in `grep $j $PAYROLL | cut -d "," -f6`
   do
    let "salariedcost = salariedcost + $i"
   done
    echo "Salaried Cost: \$${salariedcost}"
    let "totalcost = totalcost + salariedcost"
   echo "Total Cost: \$$totalcost"

   echo -en "Hit [Enter] to return to main menu..."
   read  

.txt文件:

序列如下:[id],[name],[title],[phone],[type],[pay]

3,Frank,CFO,91111453,Salaried,2333
1,Mary,CEO,93424222,Salaried,1111
5,John,Sales user,9321312,Commission,9999
7,Chris,Admin,98888753,Hourly[122]

2 个答案:

答案 0 :(得分:1)

尝试使用awk

awk -F, 'BEGIN {print "Salaried:"} $5=="Salaried"{total+=$6; printf "%s\t$%s\n", $2, $6} END {printf "Total salary: $%s", total}' $PAYROLL

输出:

Salaried:
Frank   $2333
Mary    $1111
Total salary: $3444

答案 1 :(得分:0)

awk -F',' '{print $2}' | grep "Salaried" $PAYROLL

这告诉grep打开$PAYROLL中指定的文件,搜索字符串Salaried,并在找到它时打印完整的行。 grep退出,awkSIGPIPE杀死。你可能会去做什么:

awk -F, '{print $2}' "$PAYROLL" | grep Salaried 

注意引用的细微变化。

awk模式匹配就像grep

一样
awk -F, '/Salaried/{print $2}' "$PAYROLL"

对于整个程序,你会想要这样的东西:

awk -F, '
# Before processing the first line, print out the header
BEGIN {
    print "Salaried:"
}
# Lines matching Salaried
/Salaried/ {
    # Print name <tab> salary
    print $2 "\t$" $6

    # Add their salary to our salary total
    salaries += $6
}

# Every line, add cost to total
{ 
    total += $6
}

# After processing all lines
END {
    # Print the salary total, separator, and grand total.
    print "Total Salary: $" salaries
    print "--------------------"
    print "Grand total: $" total
}' file.txt