How to match regexp with ash?

2019-04-09 18:02发布

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.

2条回答
再贱就再见
2楼-- · 2019-04-09 18:51

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楼-- · 2019-04-09 18:55

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.

查看更多
登录 后发表回答