Click to See Complete Forum and Search --> : using environment variable as replacement string in 'sed'


ComfortablyNumb
12-04-2002, 09:40 AM
I would like to use an environemnt variable as a replacement string in a 'sed' command. Here is what I have so far:

rundate=$(date +"%b %d, %Y %T") #current date

# I have a text file called 'rpt.txt' that contains the string 'XXXXXX'
# as a place holder for the date field. I want to replace the X's
# with the dynamic date held in the $rundate variable.

sed 's/XXXXXX/${rundate}/' rpt.txt > newrpt.txt

I've tried several format versions of the environment variable but to no avail. I always get literally what's in the replacement field.

In this case my report ends up with 'Run Date: ${rundate}' which is abviously not what I would like.

Any help is greatly appreciated.

Long Live the Floyd!

bwkaz
12-04-2002, 02:03 PM
Use double quotes instead of single quotes in your sed script.

With single quotes, dollar signs inside the expression aren't interpreted by the shell, but with double quotes they are. The shell is the only thing that directly knows about your variable, so it seems to me to be the best place to do the substitution.

Anyway, try sed "s/XXXXXX/${rundate}/" rpt.txt > newrpt.txt and see if that works any better. You'll have to be careful if you want other dollar signs in your sed script ever -- you'll need to escape them for the shell.

ComfortablyNumb
12-04-2002, 03:20 PM
bwkaz

That worked like a charm. Thanks very much. I should have rememberd the single versus double quote rule. I'll remember it for the next issue.

:D :D :D :D :D :D