【问题标题】:grep 'post_content' while parsing with cat & pipe into 'post_name'.htmlgrep 'post_content' 同时用 cat & pipe 解析成 'post_name'.html
【发布时间】:2018-10-02 07:35:53
【问题描述】:

示例条目:

  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我不知道这样做。

【问题讨论】:

    标签: unix sed grep yaml cat


    【解决方案1】:

    试试:

    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&gt;$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`。

    【讨论】:

    • 这有效,但命名为 *post_name*[space].yaml 但它有效 :) 谢谢!
    • @TheRojam 很高兴它对你有用。关于不需要的空间的问题,我无法重现。如果你仍然有这个问题,请告诉我更多关于你在做什么以及它与我运行的示例有何不同。
    • 使用哪个操作系统? macOS 还是 Linux?我在zsh的Linux下使用了这个。
    • @TheRojam 我使用带有 bash 的 Linux。
    • 发现问题 :D zsh 对此命令的解释与 bash 不同 :D
    猜你喜欢
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 2011-12-28
    • 2016-05-05
    相关资源
    最近更新 更多