mirror of
https://github.com/mikefarah/yq.git
synced 2026-09-01 14:14:52 +08:00
Added sort_by operator
This commit is contained in:
@@ -1,19 +0,0 @@
|
||||
|
||||
## Sort by string field
|
||||
Given a sample.yml file of:
|
||||
```yaml
|
||||
- a: banana
|
||||
- a: cat
|
||||
- a: apple
|
||||
```
|
||||
then
|
||||
```bash
|
||||
yq eval 'sort_by(.a)' sample.yml
|
||||
```
|
||||
will output
|
||||
```yaml
|
||||
- a: apple
|
||||
- a: banana
|
||||
- a: cat
|
||||
```
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Sort
|
||||
|
||||
Sorts an array. Use `sort` to sort an array as is, or `sort_by` to sort by a particular subfield.
|
||||
|
||||
Note that at this stage, `yq` only sorts scalar fields.
|
||||
@@ -0,0 +1,98 @@
|
||||
# Sort
|
||||
|
||||
Sorts an array. Use `sort` to sort an array as is, or `sort_by` to sort by a particular subfield.
|
||||
|
||||
Note that at this stage, `yq` only sorts scalar fields.
|
||||
|
||||
## Sort by string field
|
||||
Given a sample.yml file of:
|
||||
```yaml
|
||||
- a: banana
|
||||
- a: cat
|
||||
- a: apple
|
||||
```
|
||||
then
|
||||
```bash
|
||||
yq eval 'sort_by(.a)' sample.yml
|
||||
```
|
||||
will output
|
||||
```yaml
|
||||
- a: apple
|
||||
- a: banana
|
||||
- a: cat
|
||||
```
|
||||
|
||||
## Sort is stable
|
||||
Note the order of the elements in unchanged when equal in sorting.
|
||||
|
||||
Given a sample.yml file of:
|
||||
```yaml
|
||||
- a: banana
|
||||
b: 1
|
||||
- a: banana
|
||||
b: 2
|
||||
- a: banana
|
||||
b: 3
|
||||
- a: banana
|
||||
b: 4
|
||||
```
|
||||
then
|
||||
```bash
|
||||
yq eval 'sort_by(.a)' sample.yml
|
||||
```
|
||||
will output
|
||||
```yaml
|
||||
- a: banana
|
||||
b: 1
|
||||
- a: banana
|
||||
b: 2
|
||||
- a: banana
|
||||
b: 3
|
||||
- a: banana
|
||||
b: 4
|
||||
```
|
||||
|
||||
## Sort by numeric field
|
||||
Given a sample.yml file of:
|
||||
```yaml
|
||||
- a: 10
|
||||
- a: 100
|
||||
- a: 1
|
||||
```
|
||||
then
|
||||
```bash
|
||||
yq eval 'sort_by(.a)' sample.yml
|
||||
```
|
||||
will output
|
||||
```yaml
|
||||
- a: 1
|
||||
- a: 10
|
||||
- a: 100
|
||||
```
|
||||
|
||||
## Sort, nulls come first
|
||||
Given a sample.yml file of:
|
||||
```yaml
|
||||
- 8
|
||||
- 3
|
||||
- null
|
||||
- 6
|
||||
- true
|
||||
- false
|
||||
- cat
|
||||
```
|
||||
then
|
||||
```bash
|
||||
yq eval 'sort' sample.yml
|
||||
```
|
||||
will output
|
||||
```yaml
|
||||
- null
|
||||
- false
|
||||
- true
|
||||
- 3
|
||||
- 6
|
||||
- 8
|
||||
- cat
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user