How to match regexp with ash?
Asked Answered
T

4

8

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.

Technicality answered 9/1, 2014 at 2:58 Comment(1)
Wow, no POSIX. Just out of curiosity, what system are you running on?Adria
A
4

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.

Adria answered 9/1, 2014 at 7:27 Comment(1)
Thanks this works. As you say it is very limited though. It is a router with very little space cant install perl or python. Might try C.Technicality
P
4

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
Pollywog answered 16/12, 2019 at 15:10 Comment(1)
Note that it is better to work with -q option, e.g.: if $(echo "$BRANCH" | grep -qiE '^(master|release)'); thenBrann
C
3

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
Claypan answered 25/3, 2015 at 8:15 Comment(0)
D
0

You can use expr.

Define the function:

match() {
    local text="${1}";
    local rexp="${2}";
    # NOTE: expr regex is anchored with '^'
    expr "${text}" : "${rexp}" > /dev/null;
}

Test the function:

if match "string" "s"; then
    echo "true"
fi;
Demaggio answered 27/6 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.