yq/pkg/yqlib/doc/operators/unique.md

68 lines
1.1 KiB
Markdown
Raw Normal View History

2021-11-03 04:00:58 +00:00
# Unique
2022-05-06 03:46:14 +00:00
This is used to filter out duplicated items in an array. Note that the original order of the array is maintained.
2021-11-03 04:00:58 +00:00
## Unique array of scalars (string/numbers)
2022-04-29 02:16:57 +00:00
Note that unique maintains the original order of the array.
2021-11-03 04:00:58 +00:00
Given a sample.yml file of:
```yaml
2023-05-09 03:51:21 +00:00
[2, 1, 3, 2]
2021-11-03 04:00:58 +00:00
```
then
```bash
2022-01-27 06:21:10 +00:00
yq 'unique' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
2023-05-09 03:51:21 +00:00
[2, 1, 3]
2021-11-03 04:00:58 +00:00
```
## Unique nulls
Unique works on the node value, so it considers different representations of nulls to be different
Given a sample.yml file of:
```yaml
2023-05-09 03:51:21 +00:00
[~, null, ~, null]
2021-11-03 04:00:58 +00:00
```
then
```bash
2022-01-27 06:21:10 +00:00
yq 'unique' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
2023-05-09 03:51:21 +00:00
[~, null]
2021-11-03 04:00:58 +00:00
```
## Unique all nulls
Run against the node tag to unique all the nulls
Given a sample.yml file of:
```yaml
2023-05-09 03:51:21 +00:00
[~, null, ~, null]
2021-11-03 04:00:58 +00:00
```
then
```bash
2022-01-27 06:21:10 +00:00
yq 'unique_by(tag)' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
2023-05-09 03:51:21 +00:00
[~]
2021-11-03 04:00:58 +00:00
```
## Unique array object fields
Given a sample.yml file of:
```yaml
2023-05-09 03:51:21 +00:00
[{name: harry, pet: cat}, {name: billy, pet: dog}, {name: harry, pet: dog}]
2021-11-03 04:00:58 +00:00
```
then
```bash
2022-01-27 06:21:10 +00:00
yq 'unique_by(.name)' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
2023-05-09 03:51:21 +00:00
[{name: harry, pet: cat}, {name: billy, pet: dog}]
2021-11-03 04:00:58 +00:00
```