How to add numbers in a string delimeted by / and store them in a variable?

66 Views Asked by At

Sample text file contains:

04/06/1991 06/05/2001 06/08/2015
 cat ".sort.txt" | while IFS='/' read -r num inta intb intc;do
    for i in "${ADDR[@]}";do
        s=$inta+$intb+$intc
    echo $s >> .sort.txt
    done
    done <<< "$IN"

Expecting the text file to become:

04/06/1991 06/05/2001 06/08/2015 2001 2012 2029
3

There are 3 best solutions below

0
On

With bash:

while IFS=" /" read -r a1 a2 a3 b1 b2 b3 c1 c2 c3; do
  echo $a1/$a2/$a3 $b1/$b2/$b3 $c1/$c2/$c3 $((${a1#0}+${a2#0}+$a3)) $((${b1#0}+${b2#0}+$b3)) $((${c1#0}+${c2#0}+$c3))
done < sort.txt

Output:

04/06/1991 06/05/2001 06/08/2015 2001 2012 2029
0
On

It is pretty easy with awk:

awk '{printf $0 OFS; for (i=1; i<=NF; i++) { split($i, arr, "/"); 
     printf "%s%s", (arr[1]+arr[2]+arr[3]), (i<NF)?OFS:RS}}' .sort.txt
04/06/1991 06/05/2001 06/08/2015 2001 2012 2029
0
On

Perl to the rescue:

echo '04/06/1991 06/05/2001 06/08/2015' \
| perl -MList::Util=sum -lane '$_ = sum split m(/) for @F; print "$_ @F"'
  • -a populates the @F array.
  • -n processes the input line by line.
  • each element of @F (a date) is split on /, the numbers are summed. Then, the original line ($_) is printed with the new values appended.

Note it works for any number of dates per line.