2021-10-30 03:14:39 +00:00
|
|
|
# Unique
|
|
|
|
|
|
|
|
This is used to filter out duplicated items in an array.
|
|
|
|
|
2022-02-06 03:41:27 +00:00
|
|
|
{% hint style="warning" %}
|
|
|
|
Note that versions prior to 4.18 require the 'eval/e' command to be specified. 
|
|
|
|
|
|
|
|
`yq e <exp> <file>`
|
|
|
|
{% endhint %}
|
|
|
|
|
2021-10-30 03:14:39 +00:00
|
|
|
## Unique array of scalars (string/numbers)
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
- 1
|
|
|
|
- 2
|
|
|
|
- 3
|
|
|
|
- 2
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-28 01:45:43 +00:00
|
|
|
yq 'unique' sample.yml
|
2021-10-30 03:14:39 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
- 1
|
|
|
|
- 2
|
|
|
|
- 3
|
|
|
|
```
|
|
|
|
|
|
|
|
## 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
|
|
|
|
- ~
|
|
|
|
- null
|
|
|
|
- ~
|
|
|
|
- null
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-28 01:45:43 +00:00
|
|
|
yq 'unique' sample.yml
|
2021-10-30 03:14:39 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
- ~
|
|
|
|
- null
|
|
|
|
```
|
|
|
|
|
|
|
|
## Unique all nulls
|
|
|
|
Run against the node tag to unique all the nulls
|
|
|
|
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
- ~
|
|
|
|
- null
|
|
|
|
- ~
|
|
|
|
- null
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-28 01:45:43 +00:00
|
|
|
yq 'unique_by(tag)' sample.yml
|
2021-10-30 03:14:39 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
- ~
|
|
|
|
```
|
|
|
|
|
|
|
|
## Unique array object fields
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
- name: harry
|
|
|
|
pet: cat
|
|
|
|
- name: billy
|
|
|
|
pet: dog
|
|
|
|
- name: harry
|
|
|
|
pet: dog
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-28 01:45:43 +00:00
|
|
|
yq 'unique_by(.name)' sample.yml
|
2021-10-30 03:14:39 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
- name: harry
|
|
|
|
pet: cat
|
|
|
|
- name: billy
|
|
|
|
pet: dog
|
|
|
|
```
|
2021-11-03 04:00:28 +00:00
|
|
|
|