Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string according to regex in bash script

I have such a string:

msg='123abc456def'

Now I need to split msg and get the result as below:

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

In python, I can do like this:

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

How to get the same result in bash script?
I've tried like this but it doesn't work:

IFS='[0-9]'    # how to define IFS with regex?
echo ${msg[@]}
like image 960
Yves Avatar asked Jan 04 '23 18:01

Yves


1 Answers

Getting the substrings with grep, and putting the output in an array using command substitution:

$ 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 (|) one or more non-digits ([^[:digit:]]+.
like image 182
heemayl Avatar answered Jan 11 '23 10:01

heemayl