#5report
function report
{
clear
echo "Name, Position, Department, Salary"
echo "========================================"
awk 'BEGIN{FS=","; RS="\n"} {printf "%s, %s, %s, %s\n", $1, $2, $3, $4}' $dataFile
awk '{total += $4}END{print total}' $dataFile
}

i am trying to print the total sum of the salary or $4 field. However i cant figure out whats wrong, i run the script and i get the total as 0.

My dataFile looks like this

John, Manager, Finance, $2000
Jack, Accountant, Finance, $1500

John, Manager, Finance, $2000
Jack, Accountant, Finance, $1500

If you take off the $ sign from the field value it might work.

[Edit] Don't disregard Salem's advice. You're lucky I didn't noticed it before. I usually don't entertain posts from people that willingly ignores the forums conduct.

sorry bout that....my net got dc-ed halfway thru posting and i copied my whole post, didnt realise that code tags wont appear when copied...

anyway i tried taking off the $ sign but it still gives me the total as 0

function report
{
clear
echo "Name, Position, Department, Salary"
echo "========================================"
awk 'BEGIN{FS=","; RS="\n"} {printf "%s, %s, %s, %s\n", $1, $2, $3, $4}' $dataFile
echo "Total:"
awk '{total += $4}END{print total}' $dataFile
}

this is my output after Aia's advice, it still doesnt work

John, Manager, Finance, 2000
Jack, Accountant, Finance, 1500
Total:
0

Hey There,

Two things, I think:

1. You're not stripping the literal dollar sign from the figures you're trying to add

2. Since you're invoking awk twice, you need to include your BEGIN def's twice

If you change the last line of your function to:

sed 's/\$//' $dataFile|awk 'BEGIN{FS=","; RS="\n"} {total += $4}END{print total}'

it should work (although it's a simplistic sed equation that assumes only one $ per line), but you could save yourself some headach by just combining the two awk statements.

Best wishes,

Mike

The shell will allow you to create multi-line awk programs, which in this case would allow you to only read the file once, AND be sure that the $4 you see printed is the $4 being summed.

awk 'BEGIN {
  print "Name, Position, Department, Salary"
  print "========================================"
  FS=","
  RS="\n"
}
{printf "%s, %s, %s, %s\n", $1, $2, $3, $4}
{total += $4}
END {
  print total
}' $dataFile
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.