parse using pattern matching in shell

大兔子大兔子 提交于 2019-12-24 12:34:18

问题


I am trying to use reqex, pattern matching, to split this string in to separate variables, abc12c20m. where:

var1=abc
var2=12
var3=20

Main string could differ for exp abc2c5m, but abc part is always the same and c and m are always in the string. One solution must work for both abc12c20m and abc2c5m.

Any help will be greatly appreciated.


回答1:


You can use BASH regex:

s='abc12c20m'
if [[ "$s" =~ ^(abc)([0-9]+)c([0-9]+)m$ ]]; then 
    var1=${BASH_REMATCH[1]}
    var2=${BASH_REMATCH[2]}
    var3=${BASH_REMATCH[3]}
fi

echo "$var1 - $var2 - $var3"
abc - 12 - 20


来源:https://stackoverflow.com/questions/27120392/parse-using-pattern-matching-in-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!