0

I have one file, for example

a 1:2:3:4:5
b 2:3:4:5:6

Output must be:

a 15
b 20

I have to add numbers from the second column on output:

echo $((${line// /+}));done < $1

sums, but I do not know how to change the separator : to (I don't know how to use tr).

0

2 Answers 2

5

You were quite close. When you have a string like 1:2:3 and you want to get the sum of the colon-separated numbers, you can use

$ var='1:2:3'
$ echo "$(( ${var//:/+} ))"
6

Applying this to your loop:

while read -r first rest; do
    printf '%s %d\n' "$first" "$(( ${rest//:/+} ))"
done < infile

where first will contain the first column and rest is the colon-separated string.

The output looks like

a 15
b 20
Sign up to request clarification or add additional context in comments.

Comments

2

Following awk may help you in same.

awk '{num=split($2,a,":");for(i=1;i<=num;i++){sum+=a[i]};print $1,sum;sum=""}'  Input_file

Output will be as follows.

a 15
b 20

Comments

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.