gpt4 book ai didi

perl - 替换多行纯文本

转载 作者:行者123 更新时间:2023-12-01 04:45:05 25 4
gpt4 key购买 nike

假设您有大量的 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。

最佳答案

$ 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

关于perl - 替换多行纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48670992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com