I need to make the sums of the numbers from alphanumeric words from a file, USING AWK.
ex: in the file i have :
rtig0143
almn3921
ptne2218
the result should be
sum 8
sum 15
sum 13
Since you insist to do it with awk:
awk -F '' '{ sum = 0; for(i=1; i<=NF; i++) sum += $i; print "sum " sum }' file
gawk, mawk or busybox awk, that is the awk typically found on Linux-based OSes, but generally not others.
(n)awk doesn't allow an empty FS.
POSIXly:
awk '{for (i = sum = 0; i++ < length;) s += substr($0, i, 1); print "sum", s}'
Same principle as Sato Katsura's answer: we're adding up all the characters on the line; when converted from string to number, the characters that are decimal digits are converted to the value of the digit, while the others are converted to 0.
Removing the non-digit characters (with gsub(/[^0-9]/, "") or preprocessing with tr -cd '0-9\n') beforehand might improve performances.
Python 3.x approach (just the alternative solution):
sum_digits.py script:
import sys
with open(sys.argv[1], 'r') as f:
for l in f:
print("sum", sum(int(d) for d in l if d.isdigit()))
Usage:
python3 sum_digits.py yourfile
The output:
sum 8
sum 15
sum 13