yq/pkg/yqlib/doc/Add.md

104 lines
1.4 KiB
Markdown
Raw Normal View History

2020-11-24 02:07:19 +00:00
Add behaves differently according to the type of the LHS:
- arrays: concatenate
- number scalars: arithmetic addition (soon)
- string scalars: concatenate (soon)
Use `+=` as append assign for things like increment. `.a += .x` is equivalent to running `.a |= . + .x`.
## Concatenate and assign arrays
Given a sample.yml file of:
```yaml
2020-12-26 22:36:33 +00:00
a: {val: thing, b: [cat, dog]}
'': null
```
then
```bash
yq eval '.a.b += ["cow"]' sample.yml
```
will output
```yaml
2020-12-26 22:36:33 +00:00
a: {val: thing, b: [cat, dog, cow]}
'': null
```
2020-11-24 02:07:19 +00:00
## Concatenate arrays
Given a sample.yml file of:
```yaml
2020-12-26 22:36:33 +00:00
a: [1, 2]
b: [3, 4]
'': null
2020-11-24 02:07:19 +00:00
```
then
```bash
yq eval '.a + .b' sample.yml
```
will output
```yaml
2020-12-26 22:36:33 +00:00
[1, 2, 3, 4]
2020-11-24 02:07:19 +00:00
```
## Concatenate null to array
Given a sample.yml file of:
```yaml
2020-12-26 22:36:33 +00:00
a: [1, 2]
'': null
2020-11-24 02:07:19 +00:00
```
then
```bash
yq eval '.a + null' sample.yml
```
will output
```yaml
2020-12-26 22:36:33 +00:00
[1, 2]
2020-11-24 02:07:19 +00:00
```
## Add object to array
Given a sample.yml file of:
```yaml
2020-12-26 22:36:33 +00:00
a: [1, 2]
c: {cat: meow}
'': null
2020-11-24 02:07:19 +00:00
```
then
```bash
yq eval '.a + .c' sample.yml
```
will output
```yaml
2020-12-26 22:36:33 +00:00
[1, 2, {cat: meow}]
2020-11-24 02:07:19 +00:00
```
## Add string to array
Given a sample.yml file of:
```yaml
2020-12-26 22:36:33 +00:00
a: [1, 2]
'': null
2020-11-24 02:07:19 +00:00
```
then
```bash
yq eval '.a + "hello"' sample.yml
```
will output
```yaml
2020-12-26 22:36:33 +00:00
[1, 2, hello]
2020-11-24 02:07:19 +00:00
```
## Update array (append)
Given a sample.yml file of:
```yaml
2020-12-26 22:36:33 +00:00
a: [1, 2]
b: [3, 4]
'': null
2020-11-24 02:07:19 +00:00
```
then
```bash
yq eval '.a = .a + .b' sample.yml
```
will output
```yaml
2020-12-26 22:36:33 +00:00
a: [1, 2, 3, 4]
b: [3, 4]
'': null
2020-11-24 02:07:19 +00:00
```