简体   繁体   中英

Find and replace in bash

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?

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.

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

尝试:

cat app.config|sed 's/{{KEY}}/something/g'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM