假设您有大量的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。
发布于 2018-02-08 03:16:31
$ 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发布于 2018-02-08 03:51:02
$ awk 'FNR==NR{a[$1]=$2; next} ($3":" in a){sub(/$/,"\n description: "a[$3":"])}1' list RS= ORS="\n\n" file.yamlFNR==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: foobarhttps://stackoverflow.com/questions/48670992
复制相似问题