背景

配置 yaml 文件时会遇到需要将配置的内容按照键值排序的情况,比如下面这样riscv_fork_list.yaml

packages:
- name: accumulo
- name: abseil-cpp
- name: acpica-tools
- name: acpid
- name: activemq
- name: afflib
- name: adcli
- name: adwaita-icon-theme
- name: aide
- name: alsa-lib
- name: amtk
- name: anaconda
- name: apache-sshd
- name: annobin
- name: antlr3
- name: apache-commons-csv
- name: aom
- name: apache-commons-beanutils
- name: apache-commons-daemon
- name: apache-commons-el
- name: apache-commons-exec
- name: apache-commons-jexl
- name: apache-poi
- name: apache-rat

我想按照 name 的字母顺序排序,可以使用 yq 工具来实现。

安装 yq

wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/bin/yq &&\
    chmod +x /usr/bin/yq

使用 yq

yq -i '.packages |= sort_by(.name)' riscv_fork_list.yaml
packages:
- name: abseil-cpp
- name: accumulo
- name: acpica-tools
- name: acpid
- name: activemq
- name: adcli
- name: adwaita-icon-theme
- name: afflib
- name: aide
- name: alsa-lib
- name: amtk
- name: anaconda
- name: annobin
- name: antlr3
- name: aom
- name: apache-commons-beanutils
- name: apache-commons-csv
- name: apache-commons-daemon
- name: apache-commons-el
- name: apache-commons-exec
- name: apache-commons-jexl
- name: apache-poi
- name: apache-rat
- name: apache-sshd