1

How do I pass variables into a grep command? This hard-coded value is working:

startingLine=`grep -oP '(2017-01-03 )\w+.+' cv-batch.log | head -1`
echo $startingLine

But when I try to use a variable, it stops working:

currDate=$(date -d "$dataset_date" +%Y-%m-%d)
echo $currDate
startingLine=`grep -oP '($currDate )\w+.+' cv-batch.log | head -1`

Edit: I tried the following but it didn't work either:

startingLine=`grep -oP '("$currDate" )\w+.+' cv-batch.log | head -1`
Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233
Raj
  • 121

1 Answers1

5

The variable isn't "passed" since it's in single quotes. The shell will not do variable expansion within single quotes. Use double quotes instead to have the shell expand the variable's value before calling grep:

startingLine="$( grep -oP "($currDate )\w+.+" cv-batch.log | head -1)"

Notice that the variable is never actually "passed" to grep, but that it's its expanded value that is used when the shell executes the utility. Try running this by first enabling tracing (set -x) to see what actually goes on when you run it (disable tracing with set +x afterwards).

I've also used the more robust (and better looking) command substitution syntax $( ... ), and quoted the whole resulting string to avoid any problems with file name globbing and word splitting.

You should also double quote the $currDate in the echo:

echo "$currDate"

or

printf '%s\n' "$currDate"

See

Kusalananda
  • 333,661