Reputation: 1445
120h2m12s
=> 120h 2m 12s
120a2b12c
=> 120a 2b 12c
I want to split whenever a number appears after a non-number.
How can I achieve this in bash?
Here is what I tried so far:
$ echo "120h2m12s" | sed 's/[hm]/& /g'
=> 120h 2m 12s (kind of works, but I would prefer a more generally applicable solution. A way to split a string using numerals as delimiter.)Upvotes: 1
Views: 94
Reputation: 246807
I'd use perl, it's very succinct:
echo "$time" | perl -pe 's/(\D)(\d)/$1 $2/g'
But if you want bash:
$ echo "$time";
120h2m12s
$ while [[ $time =~ ([[:alpha:]])([[:digit:]]+) ]]; do
time=${time/${BASH_REMATCH[1]}${BASH_REMATCH[2]}/${BASH_REMATCH[1]} ${BASH_REMATCH[2]}}
done
$ echo "$time"
120h 2m 12s
Upvotes: 0
Reputation: 133518
Could you please try following too:
echo "120h2m12s" | sed 's/[0-9]*[a-z]*/& /g'
Output will be as follows.
120h 2m 12s
Check with another self made dummy example too:
echo "120h2m12s12131313ddd" | sed 's/[0-9]*[a-z]*/& /g'
120h 2m 12s 12131313ddd
Upvotes: 1
Reputation: 203532
$ echo '120h2m12s' | sed 's/[0-9]*/ &/g'
120h 2m 12s
You end up with a leading space using the above, if that matters then:
$ echo '120h2m12s' | sed 's/\([^0-9]\)\([0-9]\)/\1 \2/g'
120h 2m 12s
Upvotes: 1
Reputation: 2262
echo "120h2m12s" | sed -e 's/\([a-zA-Z]\)\([0-9]\)/\1 \2/g'
Adds a space in between when it sees a letter followed by a digit.
Upvotes: 0