假设您有大量的yaml文件(或类似的东西)并且您想要为具有给定名称的所有对象添加描述,例如
- name: alan
age: 8
- name: britney # some comment about britney
hobbies: ["painting", "CS"]
age: 21
- name: charles # some comment about charles
# that spans over multiple lines
age: 42
我有一个名称需要描述的对象列表,例如:
britney: teamblue
charles: foobar
如何添加包含说明的行以达到以下目的:
- name: alan
age: 8
- name: britney # some comment about britney
hobbies: ["painting", "CS"]
age: 21
description: teamblue
- name: charles # some comment about charles
# that spans over multiple lines
age: 42
description: foobar
到目前为止,我已经非常接近,但我一直未能将多行明文替换为另一行:
s=$(awk "/${name}/" RS= ./*.yml)
r=$(awk "/${name}/" RS= ./*.yml && echo " description: ${desc}")
我需要以某种方式查找$s
并将其替换为$r
,我无法使其正常工作。我尝试了以下两种的多种变体:
sed "s/$s/$r/" ./*.yml
perl -i -0pe "s/$s/$r/" ./*.yml
但不知何故,yaml中的特殊字符(换行符,双引号,......)会破坏它们,我会得到一条错误消息,如unterminated substitute pattern
或输出相同且没有匹配。
也可能与sed
相关,我使用的是macOS。
答案 0 :(得分:4)
$ cat tst.awk
NR==FNR {
sub(/:/,"",$1)
map[$1] = $2
next
}
$3 in map {
$0 = $0 "\n description: " map[$3]
}
{ print }
$ awk -f tst.awk list RS= ORS='\n\n' foo.yaml
- name: alan
age: 8
- name: britney # some comment about britney
hobbies: ["painting", "CS"]
age: 21
description: teamblue
- name: charles # some comment about charles
# that spans over multiple lines
age: 42
description: foobar
以上使用了这些输入文件:
$ cat list
britney: teamblue
charles: foobar
$ cat foo.yaml
- name: alan
age: 8
- name: britney # some comment about britney
hobbies: ["painting", "CS"]
age: 21
- name: charles # some comment about charles
# that spans over multiple lines
age: 42
答案 1 :(得分:1)
$ awk 'FNR==NR{a[$1]=$2; next} ($3":" in a){sub(/$/,"\n description: "a[$3":"])}1' list RS= ORS="\n\n" file.yaml
FNR==NR{a[$1]=$2; next}
:在阅读文件list
时,创建一个关联数组a
,其关键字为$1
,值为$2
。例如。 a[britney:]=teamblue
($3":" in a){sub(/$/,"\n description: "a[$3":"])}1
:在阅读文件file.yaml
时,如果$3":"
是a
中的密钥,则在打印前将description
添加到记录中。
<强>输出强>
- name: alan
age: 8
- name: britney # some comment about britney
hobbies: ["painting", "CS"]
age: 21
description: teamblue
- name: charles # some comment about charles
# that spans over multiple lines
age: 42
description: foobar