3

I have a YAML that looks like

something:
 - whatever:
   - something
 - toc: 4
 - body: assets/footer.html
pkg:
 - pkg_a_1:
   - Shass
   - AJh55
   - ASH7
 - pkg_b_1:
   - Kjs6
   - opsaa
other:
morestuff:
 - whatever

I would like to pull out content under pkg and print them to a text file like this:

pkg_a_1 Shass
pkg_a_1 AJh55
pkg_a_1 ASH7
pkg_b_1 Kjs6
pkg_b_1 opsaa

I am trying to avoid using a full YAML parser as I only need this one section and nothing else from a large YAML file.

  • The section label (pkg) is fixed, appears only once and does not change.
  • The subsection label and the number of subsections (pkg_a_1, pkg_b_1) can change.
  • The number of items and order of items under each subsection can change. Items can only contain [A-Za-z0-9]+.
  • Content before and after the pkg section can change. ie; the sections something: and other: may or may not be present.

3 Answers 3

3
$ awk '/^[^ ]/{ f=/^pkg:/; next } f{ if (sub(/:$/,"")) pkg=$2; else print pkg, $2 }' file
pkg_a_1 Shass
pkg_a_1 AJh55
pkg_a_1 ASH7
pkg_b_1 Kjs6
pkg_b_1 opsaa
3

Using yq from https://kislyuk.github.io/yq/

yq -r '.pkg[] | to_entries[] | .key as $key | .value[] | [ $key, . ] | @tsv' file.yaml

This transforms the YAML data into a JSON document, which yq is able to use jq expressions to work with.

The expression converts the entries of pkg into a set of objects, like these:

{
  "key": "pkg_a_1",
  "value": [
    "Shass",
    "AJh55",
    "ASH7"
  ]
}
{
  "key": "pkg_b_1",
  "value": [
    "Kjs6",
    "opsaa"
  ]
}

Each such object's value array is iterated over and an array with the key and the current value is converted into a tab-delimited list using the @tsv operator.

The final output, given the data in the question, is the tab-delimited list

pkg_a_1 Shass
pkg_a_1 AJh55
pkg_a_1 ASH7
pkg_b_1 Kjs6
pkg_b_1 opsaa
1

You could also go with Mike Farah's yq, and jq:

yq -j r infile.yml 'pkg.*' |
jq -r 'to_entries[] | .key as $k | .value | map(. = $k + " " + .) | join("\n")'

Output:

pkg_a_1 Shass
pkg_a_1 AJh55
pkg_a_1 ASH7
pkg_b_1 Kjs6
pkg_b_1 opsaa
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .