Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

looping thru' a string within a variable... 4

Status
Not open for further replies.

buccaneers

Programmer
Jun 3, 2004
28
US
Hello Guru's,

I have a string variable. Length of it is variable. With every execution this may change. But once i get a string i need to read thru it one character at a time.

How do i do it ?

I did read a thread posted by "dbadmin", it didn;t work for me.

TIA,
 
Hi,
This works with ksh
Code:
X=abcdefghi
L=${#X} # length of X
I=1
while [ $I -le $L ] # loop until I = L
do
C=$(print $X|cut -c$I) # cut the char at position $I
print $C
((I+=1)) # increment I
done
 
A 'pure' ksh version, i.e. no forks or execs....

Code:
#!/bin/ksh
r=abcdefghi
while [[ -n "$r" ]]
do
        s=${r#?}
        print ${r%$s}
        r=$s
done

(not taking anything from aau's version, it's perfectly fine, just a challenge for myself...)

Annihilannic.
 
And what about the substr operator of the expr command ? Should works for any shell ...

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
or fold the string into 1 column

Code:
r=abcdefgh
echo ${r}|fold -w1|while read char
do
 echo "char=${char}"
done

HTH,

p5wizard
 
thank you very much . This works for me. I really appreciate it.

Hv a gr8 thx giving.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top