1

I have an input file like this:

bread,5
water,15
butter,5

I want to write a script which will get the numbers from each line after the comma and add them. So the example output must be: 25

1 Answer 1

2

Use awk,

$ awk -F, '{c+=$2}END{print c}' file
25

Here -F, we are setting the Field Separator as comma. {c+=$2} would add every num exists on the second column to a variable called c . c+=$2 is equal to c = c + $2. At the last c contains the total sum of all the numbers exists on the second column. Printing c in the END block will give the final value of c variable.

Sign up to request clarification or add additional context in comments.

2 Comments

It works well, thank you! Could you explain this line for me please? c is a variable which store the price, the file should be the parameter file it is clear but how this code split by comma?
The -F option, "-F," indicates that the field separator is ","

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.