How to match regexp with ash?

时光总嘲笑我的痴心妄想 提交于 2019-12-21 19:28:24

问题


Following code works for bash but now i need it for busybox ash , which apparrently does not have "=~"

keyword="^Cookie: (.*)$"
if [[ $line =~ $keyword ]]
then
bla bla
fi

Is there a suitable replacement ?

Sorry if this is SuperUser question, could not decide.

Edit: There is also no grep,sed,awk etc. I need pure ash.


回答1:


For this particular regex you might get away with a parameter expansion hack:

if [ "$line" = "Cookie: ${line#Cookie: }" ]; then
    echo a
fi

Or a pattern matching notation + case hack:

case "$line" in
    "Cookie: "*)
        echo a
    ;;
    *)
    ;;
esac

However those solutions are strictly less powerful than regexes because they have no real Kleene star * (only .*) and you should really get some more powerful tools (a real programming language like Python?) installed on that system or you will suffer.




回答2:


Busybox comes with an expr applet which can do regex matching (anchored to the beginning of a string). If the regex matches, its return code will be 0. Example:

 # expr "abc" : "[ab]*"
 # echo $?
 0
 # expr "abc" : "[d]*"
 # echo $?
 1



回答3:


What worked for me was using Busy Box's implementations for grep and wc:

MATCHES=`echo "$BRANCH" | grep -iE '^(master|release)' | wc -l`
if [ $MATCHES -eq 0 ]; then
 echo 'Not on master or release branch'
fi


来源:https://stackoverflow.com/questions/21010882/how-to-match-regexp-with-ash

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