【问题标题】:Split massive yaml file into N valid yaml files将海量 yaml 文件拆分为 N 个有效 yaml 文件
【发布时间】:2020-01-22 23:59:49
【问题描述】:

我有一个很大的 yaml 文件:

---
foo: bar
baz:
  bacon: true
  eggs: false
---
goo: car
star:
  cheese: true
  water: false
---
dog: boxer
food:
  turkey: true
  moo: cow
---
...

我想做的是将此文件拆分为 n 个有效的 yaml 文件。

我尝试在 bash 中使用 csplit 执行此操作:

但最终会得到比我想要的更多的文件: csplit --elide-empty-files -f rendered- example.yaml "/---/" "{*}"

或最后一个文件包含大部分内容的拆分: csplit --elide-empty-files -n 3 -f rendered- app.yaml "/---/" "{3}"

这是不理想的。我真正想要的是能够说,将 yaml 文件分成三份,并在最近的分隔符处分割。我知道这并不总是真正的三分之二。

关于如何在 bash 中完成此任务的任何想法?

【问题讨论】:

  • 我不是 yml 专家。所以,不确定有效的 yml 是什么意思。对于上面的输入,你能显示输出吗? csplit --elide-empty-files -f rendered- example.yaml "/---/" "{*}" 似乎生成了有效文件。
  • @anishsane 是的,但我想要的是一个文件说分成 3 个文件,它试图在这 3 个文件中平均分配有效的 yaml。而不是在--- 上拆分并让第三个文件包含所有剩余的 yaml
  • 您可以grep -c '^---$',将其除以 3,然后将该数字用于{repetition}。例如,如果文件包含 50 个条目,请使用 csplit --elide-empty-files -n 3 -f rendered- app.yaml "/---/" "{16}"

标签: bash split yaml csplit


【解决方案1】:

我的想法不是单行的,但这是可行的。

#!/bin/bash
file=example.yaml
output=output_
count=$(cat ${file} | wc -l)
count=$((count + 1))
lines=$(grep -n -e '---' ${file} | awk -F: '{ print $1 }')
lines="${lines} ${count}"
start=$(echo ${lines} | awk '{ print $1 }')
lines=$(echo ${lines} | sed 's/^[0-9]*//')

for n in ${lines}
do
    end=$((n - 1))
    sed -n "${start},${end}p" ${file} > "${output}${start}-${end}.yaml"         
    start=$n
done

【讨论】:

  • 这好像和 csplit 很像?
  • 请告诉我你想要的结果。
【解决方案2】:

我认为没有办法用 csplit 做到这一点。我能够使用 awk 将其拆分为 1000 个 yaml 文档的文件:

awk '/---/{f="rendered-"int(++i/1000);}{print > f;}' app.yaml

要准确获取三个文件,您可以尝试以下操作:

awk '/---/{f="rendered-"(++i%3);}{print > f;}' app.yaml

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2019-01-04
    • 1970-01-01
    • 2019-01-06
    • 2012-07-19
    • 2020-05-29
    • 2011-06-22
    相关资源
    最近更新 更多