Getting at the first char of a string in Bourne shell

Mark Sicignano mark at hsi.UUCP
Mon Oct 1 02:12:24 AEST 1990


In article <9737 at jpl-devvax.JPL.NASA.GOV>, lwall at jpl-devvax (Larry Wall) writes:
 >     perl -pe 'chop; s/./$&\n/g'
 > 
 > There are lots of other ways.
 >

In article <1990Sep29.193617.25752 at iwarp.intel.com> merlyn at iwarp.intel.com (Randal Schwartz) writes:
 >
 >a="Bourne" # pretend you already have it in $a
 >first=`expr "$a" : '\(.\).*'` # to get the first char
 >a=`expr "$a" : '.\(.*\)` # to trim the first char off
 >echo "$first $a"
 >
 >[no whitespace in $a, please]
 >
 >or even:
 >
 >a="Bourne" # pretend you already have it in $a
 >eval `echo "$a" | sed 's/\(.\)\(.*\)/first=\1 a="\2"/'`
 >echo "$first $a"
 >

Double ack!  These ways might work, but what about readability!

echo "Bourne" | awk '
{
	for (i = 0; i < length; i++) {
		print substr($0, i + 1, 1);
	}
}'

Produces:
B
o
u
r
n
e

That's what you want, right?

-mark
-- 
Mark Sicignano                                  ...!uunet!hsi!mark
3M Health Information Systems                   mark at hsi.com
--



More information about the Comp.unix.shell mailing list