Reputation: 45320
How can I write a simple find and replace inside of a bash
script, but the replace comes from running a PHP script.
For example, I need to find: {{KEY}}
and replace with the output of: php -f generate_key.php
in the file app.config
. Can sed
accomplish this?
Upvotes: 1
Views: 280
Reputation: 7838
I'd suggest something along these lines instead of the sed-based solutions above:
KEY="$(php -f generate_key.php)" awk '{gsub("{{KEY}}", ENVIRON["KEY"]);print;}' < app.config > app.config.new && \
mv app.config.new app.config
(Edited at T+20h to use ENVIRON
instead of awk -v VAR=VAL
due to the latter processing escape sequences in VAL
)
Primarily because it performs the substitution without applying any interpretation or transformation to the output of your php script.
The sed-based solutions will fail if the output of your PHP script contains forward slashes, and they will also substitute various escaped characters (\n
s, \t
s etc) that are present in the output of your PHP script, which is probably not what you want.
Upvotes: 3
Reputation: 74008
Try this one
sed -e "s/{{KEY}}/`php -f generate_key.php`/g" app.config
This substitutes the replacement string with the output of the PHP script. If you want to modify app.config in place, add option -i
to the command line
sed -i -e "s/{{KEY}}/`php -f generate_key.php`/g" app.config
As @je4d has observed, if the output of generate_key.php
contains forward slashes /
, you must use another delimiter instead, for example
sed -e "s;{{KEY}};`php -f generate_key.php`;g" app.config
Upvotes: 2