Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to slice a list and write it back to a YAML file with YQ

If I have a file like this:

name: test
host: test.com
region: us-east-1
plannedMaintenancePeriods:
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500

Is it possible to replace the list with a sliced version, where plannedMaintenancePeriods only contains 5 entries?

I have tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

yq -i '.plannedMaintenancePeriods=.plannedMaintenancePeriods[0:4]' ${TENANT_METADATA_FILE}

But it seems to write the top level map into the plannedMaintenancePeriods list like so:

name: test
host: test.com
region: us-east-1
plannedMaintenancePeriods: !!map
  - name
  - test
  - host
  - test.com

>Solution :

Use the update operator |=. As it carries the context, you also don’t have to repeat the path. You can even omit the 0 at the beginning of the range, but the end is always non-inclusive, so to get 5 items you have to go up to 5:

yq -i '.plannedMaintenancePeriods |= .[:5]' file.yaml
name: test
host: test.com
region: us-east-1
plannedMaintenancePeriods:
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
  - startTime: 1679987700
    endTime: 1679992500
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading