Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter list by dictionary value in yq?

Tags:

yq

I'm using https://mikefarah.gitbook.io/yq/ . How can I filter a list of dictionaries by a particular value in a list under a particular key? In the example below I want to filter the layouts list by condition "iso3166 list contains value 'GB'".

Example

Yaml output (condensed) from xkbcli list with one model and three layouts

models:
- name: pc86
  vendor: Generic
  description: Generic 86-key PC

layouts:
- layout: 'ch'
  variant: ''
  brief: 'de'
  description: German (Switzerland)
  iso639: ['deu', 'gsw']
  iso3166: ['CH']
- layout: 'gb'
  variant: 'gla'
  brief: 'gd'
  description: Scottish Gaelic
  iso639: ['eng', 'gla']
  iso3166: ['GB', 'CA']
- layout: 'gb'
  variant: 'colemak'
  brief: 'en'
  description: English (UK, Colemak)
  iso639: ['eng']
  iso3166: ['GB']

Desired output: the two 'GB' layouts

- layout: 'gb'
  variant: 'gla'
  brief: 'gd'
  description: Scottish Gaelic
  iso639: ['eng', 'gla']
  iso3166: ['GB', 'CA']
- layout: 'gb'
  variant: 'colemak'
  brief: 'en'
  description: English (UK, Colemak)
  iso639: ['eng']
  iso3166: ['GB']

So far I've tried yq ".layouts"

like image 730
Colonel Panic Avatar asked Nov 03 '25 10:11

Colonel Panic


1 Answers

Use map and select.

# Selects by .layout
yq '.layouts | map(select(.layout == "gb"))'

# Selects by .iso3166[]
yq '.layouts | map(select(.iso3166[] == "GB"))'
- layout: 'gb'
  variant: 'gla'
  brief: 'gd'
  description: Scottish Gaelic
  iso639: ['eng', 'gla']
  iso3166: ['GB', 'CA']
- layout: 'gb'
  variant: 'colemak'
  brief: 'en'
  description: English (UK, Colemak)
  iso639: ['eng']
  iso3166: ['GB']
like image 193
pmf Avatar answered Nov 05 '25 14:11

pmf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!