0

I have to take a number as the first argument and do maths on individual digits.

The program below is supposed to output all the individual digits.

INPUT=$1
doMath() {
  awk '{split('$INPUT',a,"");printf "'${@$INPUT}'"}' 
}
doMath

I execute it with command ./armstrong_numbers.sh 657823 and get error '{split('$INPUT',a,"");printf "'${@$INPUT}'"}': bad substitution

1

You're mixing up bash with awk arrays.

Your example command splits the $INPUT into an awk array named a.
Also, you need to use BEGIN{...} instead of {...}, otherwise awk waits for input, which you don't give.

Try this,

awk 'BEGIN{split('$INPUT',a,""); for (k in a) print a[k]; }'

or better set the variable with -v to avoid problems with bad input.

awk -v "input=$INPUT" \
  'BEGIN{split(input,a,""); for (k in a) print a[k]; }'

Output is:

6
5
7
8
2
3

Or just do everything in bash:

for ((i=0;i<${#INPUT};i++)); do
  echo ${INPUT:$i:1};
done
  • I want the awk array a to be in scope of bash so that I can use bash commands to do math on individual digits. Will it be possible to it outside awk '...'? – HarshvardhanSharma Dec 6 '18 at 16:04
  • why do you use awk and not bash then in the first place? – pLumo Dec 6 '18 at 16:19
  • I get the point, I'll try with bash only. – HarshvardhanSharma Dec 6 '18 at 16:21
  • added a bash way to do it – pLumo Dec 6 '18 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.