Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match regexp with ash?

Tags:

regex

ash

busybox

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.

like image 525
user3155036 Avatar asked Jan 09 '14 02:01

user3155036


People also ask

How do I match a regex pattern?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do you match exact strings?

We can match an exact string with JavaScript by using the JavaScript string's match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.

How do you match a name in regex?

p{L} => matches any kind of letter character from any language. p{N} => matches any kind of numeric character. *- => matches asterisk and hyphen. + => Quantifier — Matches between one to unlimited times (greedy)


3 Answers

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.


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
like image 37
Alex D Avatar answered Oct 18 '22 05:10

Alex D


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
like image 3
Richard Nienaber Avatar answered Oct 18 '22 06:10

Richard Nienaber