I would like to replace a set of strings into a new file. Source file file1.json values has to be replaced by values from file1.config into file file2.json. I have following script that is failing to do so.
file1.json
JavaScript
x
{
"colorsArray":[{
"red":"$ALERT_LEVEL",
"green":"$NORMAL_LEVEL",
"blue":"$RELAX_LEVEL"
}
]
}
file1.config
JavaScript
[root@ip10]# cat file1.config
ALERT_LEVEL=DANGER
NORMAL_LEVEL=NORMAL
RELAX_LEVEL=RELAX
run.sh
JavaScript
#!/bin/bash
set -x
if [ $# -ne 3 ]; then
echo "USAGE:
./$0 file1.json file2.json file1.config"
exit 1
fi
echo "#!/bin/bash
cat > $2 << EOF
`cat $1`
EOF" > $2;
chmod +x $2;
# load variables into env
. $3
# actually replace variables
./$2
Error:
JavaScript
[root@ip10]# ./run2.sh file1.json file2.json file1.config
./file2.json: line 11: warning: here-document at line 2 delimited by end-of-file (wanted `EOF')
file2.json appears, but it has no values replaced.
JavaScript
root@ip10]# cat file2.json
{
"colorsArray":[{
"red":"",
"green":"",
"blue":""
}
]
}
Advertisement
Answer
Just explaining the comment of @user3159253. Your file1.config should look like this for your code to work properly:
JavaScript
export ALERT_LEVEL=DANGER
export NORMAL_LEVEL=NORMAL
export RELAX_LEVEL=RELAX
P.S. IMHO the way you do the thing is a bit overelaborate. I’d prefer using sed
to complete this task — takes only one string:
JavaScript
sed file1.json -e 's/$ALERT_LEVEL/DANGER/g' -e's/$NORMAL_LEVEL/NORMAL/g' -e's/$RELAX_LEVEL/RELAX/g' >file2.json