2

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

3 Answers 3

5

Since you insist to do it with awk:

awk -F '' '{ sum = 0; for(i=1; i<=NF; i++) sum += $i; print "sum " sum }' file
2
  • Note that it assumes gawk, mawk or busybox awk, that is the awk typically found on Linux-based OSes, but generally not others. Commented May 10, 2017 at 16:01
  • 1
    @StéphaneChazelas Right, traditional (n)awk doesn't allow an empty FS. Commented May 10, 2017 at 16:08
2

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.

1

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.