Question

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?

Was it helpful?

Solution

$ 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`

OTHER TIPS

How about:

$ str="define('DB_NAME', 'somedb');"
$ php -r "$str echo DB_NAME;"
somedb

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.

This might do what you want

sed -e "/DB_NAME/ s/define('DB_NAME', '\(.*\)');/\1/" /path/to/file/to/search.txt

something like this :

MATCHED=$(sed -n "s/^define('DB_NAME', '\(.*\)')/\1/p" file.php)

if [[ -n ${MATCHED} ]];then
  echo $MATCHED
else
  echo "No match found"
fi

just use the case/esac construct

mystring="define('DB_NAME', 'somedb');"
case $mystring in
    *define*DB_NAME*) 
      dbname=${mystring%\'*}
      dbname=${dname##*\'}
      echo "$dbname" ;;
esac
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top