Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell equivalent of php preg_match?

Is there a shell equivalent of PHP's preg_match?

I'm trying to extract the database name from this string in a shell script.

define('DB_NAME', 'somedb');

Using preg_match in PHP I could just do something like this.

preg_match('define(\'DB_NAME\','(.*)'\'\)',$matches);
echo $matches[1];

How can I accomplish the same thing in a shell script?

like image 932
Andrew Hopper Avatar asked Sep 15 '09 04:09

Andrew Hopper


People also ask

What does Preg_match mean in PHP?

Definition and Usage The preg_match() function returns whether a match was found in a string.

What is the difference between Preg_match and Preg_match_all?

preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.

What value is return by Preg_match?

Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

What is Preg_match in JS?

Use preg_match in JavaScript match() method is used to match a string against a regular expression and returns an array with the matches. It will return null if no match is found.


2 Answers

Use of expr answers exactly to the question :

expr match "string" "regexp"

So, for your need, you may write :

expr match "$mystring" "define('DB_NAME', '\([^']\+\)');"

Note the \( \) pair. Without these characters, expr will return the number of matched chars. With them, only the matching part is returned.

$ string="define('DB_NAME', 'toto');"
$ expr match "$string" "define('DB_NAME', '[^']\+');"
26

$ string="define('DB_NAME', 'toto');"
$ expr match "$string" "define('DB_NAME', '\([^']\+\)');"
toto

I don't know under which environments expr is available (and has this behaviour), though.

like image 193
Pierre-Olivier Vares Avatar answered Sep 22 '22 01:09

Pierre-Olivier Vares


$ t="define('DB_NAME', 'somedb');"
$ echo $t
define('DB_NAME', 'somedb');
$ eval "result=(${t##*,}"
$ echo $result
somedb
$ 

That one does contain a bashism, and while it will work in most out-of-the-box environments, to stick with posix shell features, do the clunkier version:

t="define('DB_NAME', 'somedb');"
r="${t##*,}"
r="${r%);*}"
r=`eval echo $r`
like image 44
DigitalRoss Avatar answered Sep 18 '22 01:09

DigitalRoss