-1

I have list of numbers, and I want to multiply the digits within each number with each other; e.g. for the number 1234 it is 1 X 2 X 3 X 4 = 24

E.g. the following input

7675342567
098765342567
1234567890
0987654
234567
8765678
98
0999
09876543
345678
876543
87654

needs the following result:

7408800
0
0
0
5040
564480
72
0
0
20160
20160
6720

How should I proceed?

Sydney
  • 11

2 Answers2

6

You can do it this way:

<file sed 's/./&*/g;s/*$//' | bc

7408800
0
0
0
5040
564480
72
0
0
20160
20160
6720

With GNU sed, that can be simplified as:

<file sed 's/./*&/2g' | bc
1

Strictly within bash, assuming you don't overflow beyond 9 quintillion and change (9,223,372,036,854,775,807),

while IFS= read -r 
do 
  res=1
  for((i=0;i<${#REPLY};i++))
  do 
    res=$((res * ${REPLY:i:1}))
  done
  echo "$res"
done < input > output
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255