Home > Back-end >  How to cut a number into digits and add them to each other in linux
How to cut a number into digits and add them to each other in linux

Time:10-28

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.

CodePudding user response:

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}"

CodePudding user response:

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}"
  • Related