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

Advertisements

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:

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

Leave a ReplyCancel reply