skip to Main Content

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.

5

Answers


  1. 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}"
    
    
    Login or Signup to reply.
  2. 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}"
    
    Login or Signup to reply.
  3. If you have bash version 5.2 (the most recent version to this date):

    shopt -s patsub_replacement
    n=2211
    echo $((${n//?/+&}))
    
    Login or Signup to reply.
  4. 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
    
    Login or Signup to reply.
  5. 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"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search