Run through file and parse placeholder variables

我的梦境 提交于 2019-12-24 23:43:00

问题


I have been going over this for a few days and I am completely stuck. I put placeholder variables in my files which are in the following format: *$PLACEHOLDER_VAR* with the original variable being $VAR.

Original config.conf

TEST="$PLACEHOLDER_USERNAME"
TEST2="$PLACEHOLDER_PASSWORD"

What I want to do is have a deploy.sh which contains defined variables, and can run a command which will replace any placeholder variables with the defined variables, leaving it like this:

New config.conf

TEST="Tom"
TEST2="abc123"

I need a single command for my deploy.sh which will work for any placeholder variables.

$PLACEHOLDER_USERNAME -> $USERNAME -> Tom

An example (but not right) deploy.sh using username as an example

USERNAME="Tom"
PASSWORD="abc123"
FILE="config.conf"
sed -i s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g $FILE

Can anyone please help me complete this script?


回答1:


You could try something like this :

USERNAME="Tom"
PASSWORD="abc123"
FILE="config.conf"
sed -i "s/\$PLACEHOLDER_USERNAME/$USERNAME/g" $FILE
sed -i "s/\$PLACEHOLDER_PASSWORD/$PASSWORD/g" $FILE
# perl -p -i -e "s/\$PLACEHOLDER_PASSWORD/$PASSWORD/g" $FILE

I have also included a sample of the perl alternative to sed since im not sure if the sed above will do the trick.

Try #2

This should do the trick.

USERNAME="Tom"
PASSWORD="abc123"
LIST="USERNAME PASSWORD"
FILE="config.conf"
for item in $LIST; do
    eval "sed -i \"s/\$PLACEHOLDER_$item/\$$item/g\" $FILE"
done


来源:https://stackoverflow.com/questions/20241748/run-through-file-and-parse-placeholder-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!