Kamil Basista
Kamil Basista

Reputation: 33

Bash - split text and number/numbers from one var

I have one problem. I have VAR - for example:

$VAR="test12"

And I want to split it to 2 parts. But I don't know how to do this. I tried that:

SECOND_PART="${VAR: -1}"

FIRST_PART="${VAR%?}"

but this method does not include multi-digit numbers (range: 1 to 99). Thanks in advance for your help :)

Upvotes: 1

Views: 119

Answers (2)

jaypal singh
jaypal singh

Reputation: 77185

Here is another approach:

echo  ${VAR%%[0-9]*}  ${VAR##*[!0-9]}
test 12
  • ${VAR%%[0-9]*}
    Removes the longest number match from behind. So test12 will become test.

  • ${VAR##*[!0-9]}
    Removes the longest match from front. So test12 will become 12. The match states to match anything except a number.

Upvotes: 1

sehe
sehe

Reputation: 393934

echo  ${VAR//[^0-9]/}  ${VAR//[0-9]/}

This uses pattern substitution. It also assumes the form of the input is reliable (e.g. not "this12andthat98")

Upvotes: 3

Related Questions