Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write and match regular expressions in /bin/sh script?

Tags:

regex

shell

unix

sh

I am writing a shell script for a limited unix-based microkernel which doesn't have bash! the /bin/sh can't run the following lines for some reasons.

if [[ `uname` =~ (QNX|qnx) ]]; then
read -p "what is the dev prefix to use? " dev_prefix
if [[ $dev_prefix =~ ^[a-z0-9_-]+@[a-z0-9_-"."]+:.*$ ]]; then

For the 1st and 3rd lines, it complains about missing expression operator, and for the 2nd line it says no coprocess! Can anyone shed light on differences between /bin/bash and /bin/sh scripts?

like image 783
moorara Avatar asked Jun 04 '15 15:06

moorara


People also ask

How do I match a regular expression in bash?

To match regexes you need to use the =~ operator.

How do you match a regular expression?

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).

What is regex in shell script?

A regular expression (regex) is a text pattern that can be used for searching and replacing. Regular expressions are similar to Unix wild cards used in globbing, but much more powerful, and can be used to search, replace and validate text.


1 Answers

You can use this equivalent script in /bin/sh:

if uname | grep -Eq '(QNX|qnx)'; then
   printf "what is the dev prefix to use? "
   read dev_prefix
   if echo "$dev_prefix" | grep -Eq '^[a-z0-9_-]+@[a-z0-9_-"."]+:'; then
   ...
   fi
fi
like image 130
anubhava Avatar answered Sep 18 '22 23:09

anubhava