shell yq:对YAML文件中的数组切片进行排序

7kjnsjlb  于 2023-10-23  发布在  Shell
关注(0)|答案(1)|浏览(158)

样本file.yml

---
- foo: bar
  bing:
    - bong
    - bang
  people:
    - { name: pin, nicknames: ['pin', 'first'] }
    - { name: deb, nicknames: ['deb'] }
    - { name: roger, nicknames: ['roger'] }
    - { name: kenny, nicknames: ['kenny'] }
    - { name: annie, nicknames: ['annie'] }

我尝试使用yq对people对象按name排序,除了pin,它应该放在第一位。
所需输出:

---
- foo: bar
  bing:
    - bong
    - bang
  people:
    - { name: pin, nicknames: ['pin', 'first'] }
    - { name: annie, nicknames: ['annie'] }
    - { name: deb, nicknames: ['deb'] }
    - { name: kenny, nicknames: ['kenny'] }
    - { name: roger, nicknames: ['roger'] }
❯ yq -V
yq (https://github.com/mikefarah/yq/) version v4.31.2

我已经做了切片和排序,但这只会打印排序后的切片:

❯ yq '.[].people.[1:] | sort_by(.name)' file.yml
- {name: annie, nicknames: ['annie']}
- {name: deb, nicknames: ['deb']}
- {name: kenny, nicknames: ['kenny']}
- {name: roger, nicknames: ['roger']}

不知道怎么把剩下的放回去,或者我是否在正确的轨道上。

yc0p9oo0

yc0p9oo01#

❯ yq '.[].people.[1:] | sort_by(.name)' file.yml
实际上,只将|更改为|=,以便在保留原始上下文的情况下对数组切片执行update操作,就可以完成这项工作(对于kislyuk/yq确实如此)。然而,对于mikefarah/yq,由于某种原因,数组返回时没有排序:

yq '.[].people.[1:] |= sort_by(.name)' file.yml
---
- foo: bar
  bing:
    - bong
    - bang
  people:
    - {name: pin, nicknames: ['pin', 'first']}
    - {name: deb, nicknames: ['deb']}
    - {name: roger, nicknames: ['roger']}
    - {name: kenny, nicknames: ['kenny']}
    - {name: annie, nicknames: ['annie']}

所以,你可以手动地把第一个元素切掉,然后把它重新添加到独立排序的数组切片中:

yq '.[].people |= .[:1] + (.[1:] | sort_by(.name))' file.yml
---
- foo: bar
  bing:
    - bong
    - bang
  people:
    - {name: pin, nicknames: ['pin', 'first']}
    - {name: annie, nicknames: ['annie']}
    - {name: deb, nicknames: ['deb']}
    - {name: kenny, nicknames: ['kenny']}
    - {name: roger, nicknames: ['roger']}

相关问题