2021-11-03 04:00:58 +00:00
|
|
|
# Keys
|
|
|
|
|
|
|
|
Use the `keys` operator to return map keys or array indices.
|
|
|
|
|
|
|
|
## Map keys
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
dog: woof
|
|
|
|
cat: meow
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq 'keys' sample.yml
|
2021-11-03 04:00:58 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
- dog
|
|
|
|
- cat
|
|
|
|
```
|
|
|
|
|
|
|
|
## Array keys
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
- apple
|
|
|
|
- banana
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq 'keys' sample.yml
|
2021-11-03 04:00:58 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
- 0
|
|
|
|
- 1
|
|
|
|
```
|
|
|
|
|
2021-11-23 23:16:48 +00:00
|
|
|
## Retrieve array key
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
- 1
|
|
|
|
- 2
|
|
|
|
- 3
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq '.[1] | key' sample.yml
|
2021-11-23 23:16:48 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
1
|
|
|
|
```
|
|
|
|
|
|
|
|
## Retrieve map key
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
a: thing
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq '.a | key' sample.yml
|
2021-11-23 23:16:48 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
a
|
|
|
|
```
|
|
|
|
|
|
|
|
## No key
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
{}
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq 'key' sample.yml
|
2021-11-23 23:16:48 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
```
|
|
|
|
|
2021-11-23 22:57:35 +00:00
|
|
|
## Update map key
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
a:
|
|
|
|
x: 3
|
|
|
|
y: 4
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq '(.a.x | key) = "meow"' sample.yml
|
2021-11-23 22:57:35 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
a:
|
|
|
|
meow: 3
|
|
|
|
y: 4
|
|
|
|
```
|
|
|
|
|
|
|
|
## Get comment from map key
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
a:
|
|
|
|
# comment on key
|
|
|
|
x: 3
|
|
|
|
y: 4
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq '.a.x | key | headComment' sample.yml
|
2021-11-23 22:57:35 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
comment on key
|
|
|
|
```
|
|
|
|
|