Home > Net >  How to create a for loop that reads each character in ksh
How to create a for loop that reads each character in ksh

Time:05-08

I'm unable to find any for loop syntax that works with ksh for me. I'm wanting to create a program that esentially will add up numbers that are assigned to letters when a user inputs a word into the program. I want the for loop to read the first character, grab the number value of the letter, and then add the value to a variable that starts out equaled to 0. Then the next letter will get added to the variable's value and so on until there are no more letters and there will be a variable from the for loop that equals a value.

I understand I more than likely need an array that specifies what a letter's (a-z) value would be (1-26)...which I am finding difficult to figure that out as well. Or worst case I figure out the for loop and then make about 26 if statements saying something like if the letter equals c, add 3 to the variable.

So far I have this (which is pretty bare bones):

#!/bin/ksh

typeset -A my_array
my_array[a]=1
my_array[b]=2
my_array[c]=3

echo "Enter a word: \c"
read work

for (( i=0; i<${work}; i   )); do
echo "${work:$i:1}"
done

Pretty sure this for loop is bash and not ksh. And the array returns an error of typeset: bad option(s) (I understand I haven't specified the array in the for loop).

I want the array letters (a, b, c, etc) to correspond to a value such as a = 1, b = 2, c = 3 and so on. For example the word is 'abc' and so it would add 1 2 3 and the final output will be 6.

CodePudding user response:

You were missing the pound in ${#work}, which expands to 'length of ${work}'.

#!/bin/ksh

typeset -A my_array
my_array[a]=1
my_array[b]=2
my_array[c]=3

read 'work?enter a word: '

for (( i=0; i<${#work}; i   )); do
    c=${work:$i:1} w=${my_array[${work:$i:1}]}

    echo "$c: $w"
done

ksh2020 supports read -p PROMPT syntax, which would make this script 100% compatible with bash. ksh93 does not. You could also use printf 'enter a word: ', which works in all three (ksh2020, ksh93, bash) and zsh.

Both ksh2020 and ksh93 understand read var?prompt which I used above.

CodePudding user response:

First check the input work, you only want {a..z}.

charwork=$(tr -cd "[a-z]" <<< "$work")

Next you can fill 2 arrays with corresponding values

a=( {a..z} )
b=( {1..26} )

Using these arrays you can make a file with sed commands

for ((i=0;i<26;i  )); do echo "s/${a[i]}/${b[i]} /g"; done > replaceletters.sed
# test it
echo "abcz" | sed -f replaceletters.sed
# result: 1 2 3 26 

Before you can pipe this into bc, use sed to remove the last character.
Append s/ $/\n/ to replaceletters.sed and bc can calculate it.

Now you can use sed for replacing letters by digits and insert signs.
Combining the steps, you have

tr -cd "[a-z]" <<< "$work" |
  sed -f <(
    for ((i=0;i<26;i  )); do
      echo "s/${a[i]}/${b[i]} /g"
    done
    echo 's/ $/\n/'
  ) | bc
  • Related