Subject: Re: Bourne shell script help
To: Andy Ruhl <acruhl@gmail.com>
From: Greg A. Woods <woods@weird.com>
List: netbsd-users
Date: 07/26/2006 14:31:43
--pgp-sign-Multipart_Wed_Jul_26_14:31:40_2006-1
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: quoted-printable

At Tue, 25 Jul 2006 12:29:31 -0700,
Andy Ruhl wrote:
>=20
> I'm not much of a scripter, but I need to do something specific and
> I'm hoping someone can help.
>=20
> This must be a /bin/sh script for portability, and I need to take 2
> characters off of a 14 or so character string and process them
> separately in order to know how to continue. If there is some common
> unix binary that does it, that would be fine, but it would be
> preferable to do it with built in function I guess. Seems like there
> is something that can easily do this, I just don't know what it is.
>=20
> So it would be something like this:
>=20
> string=3D<some 14 character alphanum string>
>=20
> firstchar =3D "$(`cat $string | getfirstchar`)"
> secondchar =3D "$(`cat $string | getsecondchar`)"
>=20
> Or something.
>=20
> Any help would be appreciated.

Being a minimalist sometimes, I hate to waste fork/exec cycles and so I
often try to do things like this in the fewest possible commands (though
depending on shell implementations one might find this is still forks
(and execs in) as many processes as the two-line expr example):

$ S=3Dteststring
$ eval $(echo $S | sed 's/^\(.\)\(.\).*/A=3D\1;B=3D\2/')
$ echo $A
t
$ echo $B
e
$=20

or instead of the echo and sed pipeline it can be done in an equally
portable AWK one-liner like this, guaranteeing just one fork+exec:

$ eval $(awk 'END {s =3D "'$S'"; printf("A=3D%c;B=3D%c\n", substr(s, 1, 1),=
 substr(s, 2, 1));}' < /dev/null)

Some AWK implementations, including all the POSIX compliant ones, have
a way to set a variable value from the command line, and that may make
your head spin a wee bit less with the necessary nested quoting:

$ eval $(awk -v s=3D"$S" 'END {printf("A=3D%c;B=3D%c\n", substr(s, 1, 1), s=
ubstr(s, 2, 1));}' < /dev/null)

--=20
						Greg A. Woods

H:+1 416 218-0098 W:+1 416 489-5852 x122 VE3TCP RoboHack <woods@robohack.ca>
Planix, Inc. <woods@planix.com>       Secrets of the Weird <woods@weird.com>

--pgp-sign-Multipart_Wed_Jul_26_14:31:40_2006-1
Content-Type: application/pgp-signature
Content-Transfer-Encoding: 7bit

-----BEGIN PGP SIGNATURE-----
Version: PGPfreeware 5.0i for non-commercial use
MessageID: 6IeUbulmsfQdddp2TZxIwZ/N7Ix0//kv

iQA/AwUBRMe1DmJ7XxTCWceFEQJ8IgCfSEBazk8RwZ/p3SQfl+/HqDaBz90An282
1HXxdcZtQeM3/b72TI7ApJXX
=6FtS
-----END PGP SIGNATURE-----

--pgp-sign-Multipart_Wed_Jul_26_14:31:40_2006-1--