XYZ_Linux
XYZ_Linux

Reputation: 3597

How to split a string in shell

I have a variable as

string="ABC400p2q4".

how can I separate ABC400 and p2q4. I need to separate it in two variables in such a way that as a result I get

echo $var1
ABC400
echo $var2
p2q4

In place of ABC there can be any alphabetic characters; in place of 400 there can be any other digits; but p and q are fixed and in place of 2 and 4 as well there can be any digit.

Upvotes: 5

Views: 21021

Answers (4)

Spencer Rathbun
Spencer Rathbun

Reputation: 14910

The answer provided by sudo_O is perfect if your strings stay single length. But, if that isn't the case, bash does provide you with string regex matching builtins.

$ string="ABC400p2q4"

$ var1=$( expr match "$string" '\(.{6}\)' )

$ var2=$( expr match "$string" '.*\(.{4}\)' )

Replace the regex with whatever you actually need.

Upvotes: 2

Gilles Quénot
Gilles Quénot

Reputation: 185530

Try doing this

using & process substitution (non fixed length) :

read var1 var2 < <(sed -r 's/^[a-zA-Z]+[0-9]+/& /' <<< 'ABC400p2q4')

or this using a here-string

read var1 var2 <<< $(sed -r 's/^[a-zA-Z]+[0-9]+/& /' <<< 'ABC400p2q4')

or with the short sed substitution version from Kent

's/([0-9])p/\1 p/'

Note

& in the sed command stands for the matching left part of the substitution s///

Output

$ echo $var1
ABC400
$ echo $var2
p2q4

Upvotes: 3

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185530

Using and special BASH_REMATCH array (non fixed length) :

$ string='ABC400p2q4'
$ [[ $string =~ ^([a-zA-Z]+[0-9]+)(.*) ]]
$ echo ${BASH_REMATCH[1]}
ABC400
$ echo ${BASH_REMATCH[2]}
p2q4

Upvotes: 6

Chris Seymour
Chris Seymour

Reputation: 85845

No need to split based on a regexp pattern as they are fixed length substrings. In pure bash you would do:

$ string="ABC400p2q4"

$ var1=${string:0:6}

$ var2=${string:6}

$ echo $var1
ABC400

$ echo $var2
p2q4

Upvotes: 7

Related Questions