Linux Tips and Tricks

Linux Tips and Tricks

Sum of all digits in a given number using unix commands

September18

Using the below commands, we can sum of all the digits in a given number.

Eg:

If a given number is 123. Then the answer should be ( 1 + 2 + 3 ) = 6

1
2
3
4
5
6
7
8
9
10
$ echo "1234567" | grep -o . | awk '{a+=$0}END{print a}'
28
$ echo "1234567" | awk '{for (i=1;i <=length($0);i++)a+=substr($0,i,1);print a}'
28
$ echo "1234567" | fold -w1 | awk '{a+=$0}END{print a}'
28
$ echo "1234567" | sed "s/./&\n/g" | awk '{a+=$0}END{print a}'
28
$ echo "1234567" | awk '{for(i=1;i <=NF;i++){a+=$i;}print a}' FS=
28

 

posted under Uncategorized

Email will not be published

Website example

Your Comment:


Recent Comments

    Categories