How do I insert a script variable into a regex string?
I'm writing a script that is trying to insert a directory name into a pax co开发者_Go百科mmand 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!
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
精彩评论