Picking a character from a word

John Rupley rupley at arizona.edu
Sun Apr 24 08:47:54 AEST 1988


In article <578 at amethyst.ma.arizona.edu>, barsam at eros.ame.arizona.edu (Barsam Marasli) writes:
> I have a csh question.
> I would like to have a script that will echo, say the 4th character
> of an arguement. I came up with the following:
> 
> set word=`echo $1 | od -c` ; echo $word[5]
> 
> which seems to do the job but somehow I feel like there are
> more elegant ways of doing this. Please reply by e-mail or
> post. Also what's an alternative in sh? Thanx.

It can be done rather neatly the Korn shell:

	aaa=${1#???};echo ${aaa%${1#????}}

Incorporates only shell commands.  Satisfies the test, "use the 
simplest tool."  Reasonably elegant.  And it's fast - for timing, see 
the test output below, which compares the above and several other 
suggestions.

John Rupley
 uucp: ..{ihnp4 | hao!noao}!arizona!rupley!local
 internet: rupley!local at megaron.arizona.edu
 telex: 9103508679(JARJAR)
 (H) 30 Calle Belleza, Tucson AZ 85716 - (602) 325-4533
 (O) Dept. Biochemistry, Univ. Arizona, Tucson AZ 85721 - (602) 621-3929

---------------test-------------------------------
x=${1:-12345}
time (aaa=${x#???};echo ${aaa%${x#????}})
echo "\n"
time (echo $x|cut -c4)
echo "\n"
time (expr $x : '...\(.\)' )
---------------output from above------------------
4

real	0m0.06s
user	0m0.01s
sys	0m0.03s


4

real	0m0.90s
user	0m0.03s
sys	0m0.73s


4

real	0m0.81s
user	0m0.06s
sys	0m0.65s



More information about the Comp.unix.questions mailing list