当您使用 awk 时,您永远不需要 sed,您可以让 shell 变量扩展为脚本的一部分,并且您的代码中还有其他 shell 错误。作为起点,您应该将所有脚本复制/粘贴到http://shellcheck.net http://shellcheck.net并修复它告诉您的错误。
这使用 GNU awk 进行“就地”编辑,因为您使用 GNU sed 来执行相同的操作:
$ cat myscript.sh
#!/usr/bin/env bash
file="$1"
shift
awk -i inplace -v vms="$*" '
/^-/ {
if ( $2 == "monitor_vms:" ) {
inBlock = 1
}
else {
prtVms()
}
}
$1 == "-" {
prev = $0
}
{ print }
END { prtVms() }
function prtVms( vmsArr, i, n) {
if ( inBlock ) {
sub(/:.*/,":",prev)
n = split(vms,vmsArr)
for (i=1; i<=n; i++) {
print prev, vmsArr[i]
}
}
inBlock = 0
}
' "$file"
$ cat my.yaml
---
- someotherkey: hello
value: some_value
- someotherkey1: hello1
value1: some_value1
- monitor_vms:
- name: sujana
cnt: 5
- name: vijaya
cnt: 5
- static_configs:
- location:
datacenter:
$ ./myscript.sh my.yaml neo1 neo2 neo3 alice1 alice2 alice3
$ cat my.yaml
---
- someotherkey: hello
value: some_value
- someotherkey1: hello1
value1: some_value1
- monitor_vms:
- name: sujana
cnt: 5
- name: vijaya
cnt: 5
- name: neo1
- name: neo2
- name: neo3
- name: alice1
- name: alice2
- name: alice3
- static_configs:
- location:
datacenter: