goofansu
goofansu

Reputation: 2277

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.

Upvotes: 0

Views: 154

Answers (2)

Mario Rossi
Mario Rossi

Reputation: 7799

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"

Upvotes: 3

devnull
devnull

Reputation: 123458

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*\""

Upvotes: 3

Related Questions