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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need to split string into 2 variables 3

Status
Not open for further replies.

TSch

Technical User
Jul 12, 2001
557
DE
Hi folks,

I'm looking for a way to split certain strings into 2 variables. There are 4 possible types of strings. Every string begins with 1 or 2 letters followed by 1 or 2 numbers.

Code:
Example 1:

String = A2
Var 1  = A
Var 2  = 2

Example 2:

String = B65
Var 1  = B
Var 2  = 65

Example 3:

String = CC4
Var 1  = CC
Var 2  = 4

Example 4:

String = DD12
Var 1  = DD
Var 2  = 12

In other words: How can I automatically part the letters from the numbers and store each one in a separate variable ?

Regards,
Thomas
 
You could use egrep I suppose
Code:
var1 = `echo $string | egrep -o -i '[A-Z]+'`
var2 = `echo $string | egrep -o '[0-9]+'`
but clunky though...

Cheers,
Scott
 
Code:
Var1=`expr "$String" : '\([A-Z]*\)[0-9]*'`
Var2=`expr "$String" : '[A-Z]*\([0-9]*\)'`

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Thanks a lot everyone !
Both methods are working perfectly ...
 
Yet another way...
Code:
#!/bin/ksh

STR=ABC123
VAR1=${STR%%[0-9]*}
VAR2=${STR##*[a-zA-Z]}
I included the she-bang line since this is Korn shell only (I believe).

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top