使用shellscript用config.json中定义的1-n特定值替换html文件中的占位符 [英] replacing a placeholder in a html file with 1-n specific values defined in a config.json using shellscript
问题描述
我需要用config.json文件中定义的1-n个特定值替换html文件index.html中的占位符( __ PLACEHOLDER __
).
I need to replace a placeholder (__PLACEHOLDER__
) in a html file index.html with 1-n specific values defined in a config.json file.
用新内容替换index.html中的占位符: echo"$ {html//__ PLACEHOLDER __/$ replace}">index.html
replacing the placeholder inside index.html with new content:
echo "${html//__PLACEHOLDER__/$replace}" > index.html
从json获取值(不起作用): replace = $(sed's/.*"host":"\(.* \)"/\ 1/g; d; t'config.json)
这不是一个好方法,目前无法返回所需的值
getting the values from json (not working):
replace=$(sed 's/.*"host": "\(.*\)"/\1/g;d;t' config.json)
this is not a good approach and currently does not return the desired values
所以我知道如何替换html文件中的值,但是在此之前我不知道如何将我需要的值转换为变量.我已经在sed或perl中使用sed进行过尝试,但是问题是它与跨平台不兼容,这是必须的.
So i know how to replace the value in the html file, but i dont know how to get the values i need into a variable before that. I already tried it with sed or perl, with sed however the issue is its not cross platform compatible which it need to be.
{
"xxxx": {
"description": "xxxxx",
"value": {
"to": [
"xxxxxx"
]
}
},
"xxxx": {
"description": "xxx",
"value": "xxxxxx"
},
"API": {
"description": "xxxxxxxxx",
"value": {
"default": {
"host": "VALUE I WANT"
},
"auth": {
"host": "VALUE I WANT"
}
}
},
}
default和auth仅是一些可能的值,它可能是1-n主机.
default and auth are only some possible values it could be 1-n hosts.
最后,我想要一个以所有主机为字符串的变量:host1 host2 host3
in the end i would like a variable with all the hosts as strings: host1 host2 host3
信息:我们不能使用系统和其他系统通常不提供的任何第三方工具.index.html文件无关紧要,我们只替换占位符的值即可.
感谢您的帮助
推荐答案
我们不能使用系统上通常不存在的任何第三方工具
we cannot use any 3rd party tools which are not usually present on systems
鉴于我们不知道您使用的是什么系统",这并不是一个非常有用的限制.
Given that we don't know what "systems" you're using, this isn't a very useful restriction to tell us about.
Perl有几个可用的JSON解析器,自Perl 5.14(于2011年5月发布)以来,其中一个(
Perl has several JSON parsers available and since Perl 5.14 (which was released in May 2011) one of them (JSON::PP) has been part of the standard Perl distribution. So if you have a version of Perl that was released in the last nine years, then the task of reading the JSON file into a variable is trivial.
#!/user/bin/perl
use strict;
use warnings;
use feature 'say';
use JSON::PP;
use Data::Dumper;
open my $json_fh, '<', 'config.json' or die $!;
my $json = do { local $/; <$json_fh> };
my $config = JSON::PP->new->decode($json);
# Now you have your JSON in a Perl data structure
say Dumper $config;
# You can also access individual values
say $config->{xxxx}{description};
say $config->{API}{value}{default}{host};
这篇关于使用shellscript用config.json中定义的1-n特定值替换html文件中的占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!