Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a script variable into a regex string?

Tags:

shell

I'm writing a script that is trying to insert a directory name into a pax command and I'm not sure how to get the syntax correct. This is what I'm trying, but it seems to be treating the $DIRNAME as part of the regex string.

DIRNAME=$(tar -tvf $1  | head -1 | sed -e 's:^.* \([^/]*\)/.*$:\1:')
pax -r -f $1 -s'/$DIRNAME\/upload\///'

Thanks!

like image 380
user77413 Avatar asked Oct 19 '25 01:10

user77413


1 Answers

Try using double quotes rather than single quotes when calling pax:

DIRNAME=$(tar -tvf $1  | head -1 | sed -e 's:^.* \([^/]*\)/.*$:\1:')
pax -r -f $1 -s"/$DIRNAME\/upload\///"

In several shells (eg bash and sh), $variables only get expanded when they occur in double-quoted strings, not single-quoted strings.


E.g., the following script:

#!/bin/sh

DIRNAME=$(echo 'hello')
echo "Single quotes around regexp:"
echo 'hello world' | sed 's/$DIRNAME/hi/'

echo "Double quotes around regexp:"
echo 'hello world' | sed "s/$DIRNAME/hi/"

Generates the output:

Single quotes around regexp:
hello world
Double quotes around regexp:
hi world
like image 115
Edward Loper Avatar answered Oct 22 '25 03:10

Edward Loper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!