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[@]}
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
[[:digit:]]+|[^[:digit:]]+
matches one or more digits ([[:digit:]]+
) OR (|
) one or more non-digits ([^[:digit:]]+
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With