Added another sort example

This commit is contained in:
Mike Farah 2021-12-05 10:59:12 +11:00
parent 1468c37e0b
commit ed03d21a0b

View File

@ -1,6 +1,6 @@
# Sort
Sorts an array. Use `sort` to sort an array as is, or `sort_by` to sort by a particular subfield.
Sorts an array. Use `sort` to sort an array as is, or `sort_by(exp)` to sort by a particular expression (e.g. subfield).
Note that at this stage, `yq` only sorts scalar fields.
@ -22,6 +22,48 @@ will output
- a: cat
```
## Sort array in place
Given a sample.yml file of:
```yaml
cool:
- a: banana
- a: cat
- a: apple
```
then
```bash
yq eval '.cool |= sort_by(.a)' sample.yml
```
will output
```yaml
cool:
- a: apple
- a: banana
- a: cat
```
## Sort array of objects by key
Note that you can give sort_by complex expressions, not just paths
Given a sample.yml file of:
```yaml
cool:
- b: banana
- a: banana
- c: banana
```
then
```bash
yq eval '.cool |= sort_by(keys | .[0])' sample.yml
```
will output
```yaml
cool:
- a: banana
- b: banana
- c: banana
```
## Sort is stable
Note the order of the elements in unchanged when equal in sorting.