grep 'post_content' 同时用 cat & pipe 解析为 'post_name'.html

grep 'post_content' while parsing with cat & pipe into 'post_name'.html

示例条目:

  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=[=10=]} /post_name:/{print content>".yaml"; close(".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=[=10=]} /post_name:/{print content>".yaml"; close(".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=[=16=]}

    每次我们到达包含 post_content: 的行时,我们将该行保存在变量 content.

  • /post_name:/{print content>".yaml"; close(".yaml")}

    每次我们到达包含 post_name: 的行时,我们打印变量 content to a file whose name is given by the second field on the line followed by.yaml`.