Getting at the first char of a string in Bourne shell

Randal Schwartz merlyn at iwarp.intel.com
Sun Sep 30 05:36:17 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.

Ack.  Just to even out the "do everything in Perl" reputation I've
gotten, here's how to do it *without* Perl.  (And I'm even doing this
as a followup to Larry's article... sheesh.  If that doesn't even out
the score, I don't know what will!)

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"

[This requires well-behaved values of $a... whitespace is OK, quoting
characters are out.]

There.  Not a single 'perl' invocation in the pile :-)

Just another Bourne-shell hacker,
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn at iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/



More information about the Comp.unix.shell mailing list