If I have a string defined as:
MyString=abcde
echo $MyString
How can I loop through it character by character? I haven't been able to find a way to index the string so that I loop through it.
shew01
If I have a string defined as:
MyString=abcde
echo $MyString
How can I loop through it character by character? I haven't been able to find a way to index the string so that I loop through it.
shew01
A possible solution :
MyString=abcde
echo $MyString | awk -v ORS="" '{ gsub(/./,"&\n") ; print }' | \
while read char
do
echo "<$char>"
done
Output:
<a>
<b>
<c>
<d>
<e>
Jean-Pierre.
Another way :
MyString=abcde
i=0
while (( i++ < ${#MyString} ))
do
char=$(expr substr "$MyString" $i 1)
echo "<$char>"
done
Jean-Pierre.
I am running the Korn shell on Solaris 8, and I am getting errors:
awk: syntax error near line 1
awk: bailing out near line 1
Any ideas?
shew01
My script name is jps.ksh. Any ideas?
jps.ksh[3]: i++ < 5 : syntax error
Do you Have tried nawk instead of awk ?
Jean-Pierre.
Sorry, this syntax works with bash but not with ksh.
Try this new version of the script :
MyString=abcde
i=1
while (( i <= ${#MyString} ))
do
char=$(expr substr "$MyString" $i 1)
echo "<$char>"
(( i += 1 ))
done
Jean-Pierre.
Good idea. nawk works.
I'm getting different errors:
expr: syntax error
<>
expr: syntax error
<>
expr: syntax error
<>
expr: syntax error
<>
expr: syntax error
<>
I've read several posts complaining about expr syntax errors. Is Solaris the culprit here?
shew01
aigles,
I think I found a workaround (see quirk at http://www.unix.com/shell-programming-scripting/64575-substr-shell-script.html\). This version of the code works:
MyString=abcde
i=1
while (( i <= ${#MyString} ))
do
char=$(/usr/ucb/expr substr "$MyString" $i 1)
echo "<$char>"
(( i += 1 ))
done
Apparently, the default version of expr, located in /usr/bin, has a bug in it. However, the version of expr located in /usr/ucb works fine.
Thanks sooooooooo much for your help!!!!! I've spent several hours on this... You definitely pointed me in the right direction.
shew01
the following may be of interest
who am i | cut -f1 -d' '|cut -c3
and also wc -m