For example 2211 needs to display 6 but I can't find a command that helps me with it. I have already tried with cut but that can only cut one at a time.
Works in Debian. Try this:
#!/bin/bash
number="2211"
result=0
for (( i=0; i<${#number}; i++ )); do
echo "number[${i}]=${number:$i:1}"
result=$(( result + ${number:$i:1} ))
done
echo "result = ${result}"
If you have bash
version 5.2 (the most recent version to this date):
shopt -s patsub_replacement
n=2211
echo $((${n//?/+&}))
Using a while
+ read
loop.
#!/usr/bin/env bash
str=2211
while IFS= read -rd '' -n1 addend; do
((sum+=addend))
done < <(printf '%s' "$str")
declare -p sum
If your bash is new enough, instead of declare
echo "${sum@A}"
Math variant probably there are more elegant variants
sum=0
num=2211
n=${#num}
for ((i=n-1; i>=0; i--)); {
a=$((10**i))
b=$((num/a))
sum=$((sum+b))
num=$((num-(b*a)))
echo $i $a $b $num $sum
}
3 1000 2 211 2
2 100 2 11 4
1 10 1 1 5
0 1 1 0 6
$ echo $sum
6
Another ( Shellcheck -clean) way to do it with arithmetic instead of string manipulation:
#! /bin/bash -p
declare -i num=2211 sum=0
while (( num > 0 )); do
sum+=num%10
num=num/10
done
echo "$sum"
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.