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?
Definition and Usage The preg_match() function returns whether a match was found in a string.
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.
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 .
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.
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.
$ 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`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With