示例条目:
post_content: " some <strong >blablablabla</strong> text in <html>"
post_title: Kontakt
post_password:
post_name: kontakt
问题:我有一个包含上述条目的 yaml 文件,我喜欢用 cat & grep 解析 post_content 的内容,并将其通过管道传输到不同的文件中。
$ cat posts.yaml | grep post_content >> different-file.yaml
这有效。很好 :) 但这样我只从 *posts.yaml 中排除所有post_content
在它上面我喜欢将每个post_content分开到名为post_name.yaml 的单独文件中- 我认为它可以用一些 sed-foo将其合并到一行 shell 命令中。但 atm 我不知道这样做。
尝试:
awk '/post_content:/{content=$0} /post_name:/{print content>$2".yaml"; close($2".yaml")}' posts.yaml
考虑这个测试文件:
$ cat posts.yaml
post_content: " some <strong >blablablabla</strong> text in <html>"
post_title: Kontakt
post_password:
post_name: kontakt
post_content: " some other text in <html>"
post_title: Kontakt
post_password:
post_name: contact
然后我们运行:
awk '/post_content:/{content=$0} /post_name:/{print content>$2".yaml"; close($2".yaml")}' posts.yaml
运行此命令后,posts.yaml
当前目录中除了 之外还会有两个新文件:
$ ls
contact.yaml kontakt.yaml posts.yaml
新文件的内容是:
$ cat kontakt.yaml
post_content: " some <strong >blablablabla</strong> text in <html>"
$ cat contact.yaml
post_content: " some other text in <html>"
/post_content:/{content=$0}
每次到达包含 的行时post_content:
,我们都会将该行保存在变量 中content
。
/post_name:/{print content>$2".yaml"; close($2".yaml")}
每次到达包含 的行时post_name:
,我们都会打印变量content to a file whose name is given by the second field on the line followed by
.yaml`。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句