From ed03d21a0b49473d1d3e7c096e0080224e2f20f4 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sun, 5 Dec 2021 10:59:12 +1100 Subject: [PATCH] Added another sort example --- operators/sort.md | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/operators/sort.md b/operators/sort.md index fbecdefc..4e9d292f 100644 --- a/operators/sort.md +++ b/operators/sort.md @@ -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.