简体   繁体   中英

Bash sum from file

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 ).

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM