简体   繁体   中英

How to use variables in bash grep?

#!/bin/bash

host=${1-localhost}
port=${2-27017}
dbname=${3-ascq}

MONGOBKDIR=./mongo_data/ascq
echo "restore data from $MONGOBKDIR"

dbs=$(mongo $host:$port --eval 'printjson(db.adminCommand("listDatabases"))' | \
            grep -oP '"name" : "${dbname}\d*"' | \
            awk '{print $3}' | tr -d '"')

for i in $dbs
do
    echo "restoring:$i"
    mongorestore -h $host:$port -d $i --drop $MONGOBKDIR/
done

exit 0

I want to use ${dbname} in grep but failed.

You are using single quotes which would prevent expansion of the variable.

Use double quotes:

grep -oP "name : ${dbname}\d*"

If you also want to match quotes " in the pattern, escape those:

grep -oP "\"name\" : \"${dbname}\d*\""

Try grep -oP '"name" : "'${dbname}'\\d*"' .

Inside apostrophes (single quotes), variable expansion does not occur.

I assume input contains quotes (double ones) that you want to match, as in

"name" : "sales34567"
"name" : "payroll34567"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM