How to split string according to regex in bash script

I have a line like this:

msg='123abc456def'

Now I need to split msgand get the result, as shown below:

['123', 'abc', '456', 'def']

In python, I can do the following:

pattern = re.compile(r'(\d+)')
res = pattern.split(msg)[1:]

How to get the same result in a bash script?
I tried like this, but this does not work:

IFS='[0-9]'    # how to define IFS with regex?
echo ${msg[@]}
+4
source share
3 answers

Getting substrings with grepand placing output in an array by replacing commands:

$ msg='123abc456def'

$ out=( $(grep -Eo '[[:digit:]]+|[^[:digit:]]+' <<<"$msg") )

$ echo "${out[0]}"
123

$ echo "${out[1]}"
abc

$ echo "${out[@]}"
123 abc 456 def
  • The Regex (ERE) pattern [[:digit:]]+|[^[:digit:]]+matches one or more digits ( [[:digit:]]+) OR ( |) to one or more non-digital numbers ( [^[:digit:]]+.
+2
source

. grep, bash.

$ msg='123abc456def'
$ grep -oE '[0-9]+|[^0-9]+' <<<$msg
123
abc
456
def
+1

, , Python, , , :

MSG=123abc456def;
python -c "import re; print('\n'.join(re.split(r'(\\d+)', '${MSG}')[1:]))"

Not pythonyet an executable file standard, such as say grepor awk, does it really matter to you?

+1
source

Source: https://habr.com/ru/post/1681162/


All Articles