[Solved] sed : last character replace

Hi all ,

I have to write a shell script that takes a number as input , like 123
and the output will be 6 ,i.e the output will be the sum of digits of the input.

I have an idea as follows,

echo "123"|fold -1|tr '\n' '+'|bc

But the problem is after " echo "123"|fold -1|tr '\n' '+' " the output is 1+2+3+ which is not working with bc.

Is there is any way to replace the last character of a line to "\n" ???

Thanking You ,
M.Choudhury :slight_smile:

 
$ echo "123" | nawk ' BEGIN{FS=""} {for(i=1;i<=length($0);i++) {a=a+substr($0,i,1)}} END{print a}'
6

Or:

echo "123" | sed -e 's/./&+/g' -e 's/.$//' | bc
1 Like

Alternatively..

echo "123"|fold -1|tr '\n' '+'| sed 's/+$/\n/'| bc
echo "123"|awk 'BEGIN{FS=""} {print $1"+"$2"+"$3}'| bc
1 Like
echo "123" | awk '$1=$1' FS= OFS=+ | bc
1 Like

Thanks everyone ... Problem Solved :slight_smile: