arrays - 仅当 counter_name 匹配时如何从 JSON 数据下方提取 counterid 并将 counterid 添加到 shell 脚本中的另一个文件
问题描述
我正在写 shellscript。
我有一个 JSON 数据。我需要提取 counterid 并将该数据传递给 .yml 文件。如果 counter_name(在 JSON 数据中)与 yml 文件中的数据匹配,我想替换 yml 文件中的数据,并用它替换为 counterid。
例子:
{"counterId" : 200001 ,"counterName" = status-total_access"}
原始 yml 文件:
- rename:
fields:
- from: "apache.status.total_kbytes"
to: "apache.status-total_kbytes"
yml 文件应更改为:
- rename:
fields:
- from: "apache.status.total_kbytes"
to: "apache.2000001"
那么,有没有办法在 shellscript 中做到这一点?
我知道有一个名为 sed 的选项,但不知道如何提取 JSON 值。
这是我的 json 数据:
[{"counterId":200001,"counterName":"status-total_accesses"},{"counterId":200002,"counterName":"status-total_kbytes"},{"counterId":200003,"counterName":"status-requests_per_sec"},{"counterId":200004,"counterName":"status-bytes_per_sec"},{"counterId":200005,"counterName":"status-bytes_per_request"},{"counterId":200006,"counterName":"workers-busy"}]
这是我的 yml 文件:
- rename:
fields:
- from: "apache.status.workers.busy"
to: "apache.workers-busy"
ignore_missing: true
- rename:
fields:
- from: "apache.status.workers.idle"
to: "apache.workers-idle"
ignore_missing: true
- rename:
fields:
- from: "apache.status.total_accesses"
to: "apache.status-total_accesses"
ignore_missing: true
- rename:
fields:
- from: "apache.status.total_kbytes"
to: "apache.status-total_kbytes"
ignore_missing: true
- rename:
fields:
- from: "apache.status.uptime.server_uptime"
to: "apache.uptime-server_uptime"
ignore_missing: true
解决方案
你需要像 jq 这样的东西。使用 jq 您将从每个对象中获取 counterId 和 counterName 值。为了实现这一点,首先迭代每个值,然后再次使用 jq 来提取每个字段。之后,您只需使用原始文件或副本中的值 sed 名称。
一个非常快速的实现滚滚,这会在每次做一个 sed 的时候在标准输出文件上打印整个文件。您应该使用 -i 替换值。json.in 和 yaml.in 是具有您提供的内容的输入文件。
#!/bin/bash
for row in $(cat json.in | jq -c '.[]' ); do
value=$(echo ${row}|jq '.counterId' )
name=$(echo ${row}|jq -r '.counterName' )
echo "$value $name"
sed -i "s/$name/$value/g" yaml.in
done
输出是:
- rename:
fields:
- from: "apache.status.workers.busy"
to: "apache.200006"
ignore_missing: true
- rename:
fields:
- from: "apache.status.workers.idle"
to: "apache.workers-idle"
ignore_missing: true
- rename:
fields:
- from: "apache.status.total_accesses"
to: "apache.200001"
ignore_missing: true
- rename:
fields:
- from: "apache.status.total_kbytes"
to: "apache.200002"
ignore_missing: true
- rename:
fields:
- from: "apache.status.uptime.server_uptime"
to: "apache.uptime-server_uptime"
ignore_missing: true
推荐阅读
- python-3.x - PYTHON - 如何检查我是否正确调用了这个 API?
- javascript - 我不断收到无法读取属性错误
- c - 无法更改 SASM 中的函数名称
- java - while 循环和 if/else 语句的问题
- android - 在 Robolectric 中找不到 @Config 常量参数
- java - 尽量减少循环中的重复代码
- css - 使用 GruntJS 将 SASS 转换为 CSS 时的空 CSS 文件输出
- mysql - 等效于 H2 DB 的 UNIX_TIMESTAMP 函数?
- java - 使用 java 验证 Outlook 电子邮件地址
- angular - Http请求标头无法正常工作,Angular 5