yq/pkg/yqlib/doc/operators/headers/multiply-merge.md

38 lines
1.5 KiB
Markdown
Raw Normal View History

2021-11-03 04:00:58 +00:00
# Multiply (Merge)
Like the multiple operator in jq, depending on the operands, this multiply operator will do different things. Currently numbers, arrays and objects are supported.
2020-11-17 22:44:16 +00:00
## Objects and arrays - merging
Objects are merged deeply matching on matching keys. By default, array values override and are not deeply merged.
2020-11-22 02:16:54 +00:00
Note that when merging objects, this operator returns the merged object (not the parent). This will be clearer in the examples below.
### Merge Flags
You can control how objects are merged by using one or more of the following flags. Multiple flags can be used together, e.g. `.a *+? .b`. See examples below
2021-01-14 09:28:57 +00:00
- `+` append arrays
- `d` deeply merge arrays
- `?` only merge _existing_ fields
- `n` only merge _new_ fields
- `c` clobber custom tags
2022-03-15 23:04:13 +00:00
### Merge two files together
This uses the load operator to merge file2 into file1.
```bash
yq '. *= load("file2.yml")' file1.yml
```
### Merging all files
2021-01-14 09:28:57 +00:00
Note the use of `eval-all` to ensure all documents are loaded into memory.
2020-11-22 02:16:54 +00:00
```bash
2022-03-15 23:04:13 +00:00
yq eval-all '. as $item ireduce ({}; . * $item )' *.yml
2020-11-22 02:16:54 +00:00
```
2022-05-24 06:16:58 +00:00
# Merging complex arrays together by a key field
By default - `yq` merge is naive. It merges maps when they match the key name, and arrays are merged either by appending them together, or merging the entries by their position in the array.
For more complex array merging (e.g. merging items that match on a certain key) please see the example [here](https://mikefarah.gitbook.io/yq/operators/multiply-merge#merge-arrays-of-objects-together-matching-on-a-key)