17

I execute the following bash script:

#!/bin/bash
version=$1
echo $version
sed 's/\${version.number}/$version/' template.txt > readme.txt

I'm expecting to replace all instances of ${version.number} with the contents of the variable "version". Instead the literal text $version is being inserted.

What do I need to do to make sed use the current value of $version instead?

C. Ross
  • 31,137
  • 42
  • 147
  • 238
Steve McLeod
  • 51,737
  • 47
  • 128
  • 184

3 Answers3

22
sed "s/\${version.number}/$version/" template.txt > readme.txt

Only double quotes do dollar-sign replacement. That also means single quotes don't require the dollar sign to be escaped.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • But the dollar sign has to be escaped because the expression is treated as a regex by `sed`. So I think it should be `\\$`. – Philipp Jul 08 '10 at 14:10
  • 1
    @Philipp, actually the `$` sign is only an anchor when it's the last character of the regex (or possibly subexpression). But I admit I got lucky. ;) You can optionally add an escaped slash, but then it's `\\\$`. – Matthew Flaschen Jul 08 '10 at 14:53
  • [This](http://stackoverflow.com/a/11209079/376454) worked better for me. – Wok Jun 17 '13 at 15:06
4

You could also simply unquote the variables

sed 's/'${version.number}'/'$version'/' template.txt > readme.txt
Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221
0

It's a bit old, but it might still be helpful... For me it worked using a double escape as Philip said (and escaping parenthesis, if you use them...):

#!/bin/bash
LIVE_DB_NAME='wordpress';
STAGING='staging';
sed -r "s/define\('DB_NAME', '[a-zA-Z0-9]+'\);/define('DB_NAME', '\\${LIVE_DB_NAME}');/" ${STAGING}/wp-config.php >tmp1;
J Mac
  • 65
  • 7