Yq is a lightweight and portable command-line YAML processor. This page focuses on yq v4. For version 3, please use the yq command.
Yq v4 allows for powerful manipulation of YAML data directly from your terminal. Below are common operations and examples.
You can read specific nodes or evaluate expressions against YAML files.
# Read spec.template node from example.yml
yq eval '.spec.template' example.yml
Yq v4 excels at updating existing YAML structures. The |= operator is particularly useful for in-place modifications.
# Assign spec.selector.matchLabels to spec.template.metadata.labels
yq eval \
'.spec.selector.matchLabels |= .spec.template.metadata.labels' example.yaml
# Update parent to be the child value. b is a's child.
# '|=' means the . on the right is relative to the left.
yq eval '.a |= .b' sample.yml
# Update multiple nodes. a and c are siblings.
yq eval '(.a, .c) |= "potato"' sample.yml
# Update selected results.
# Only update a's children with value=='apple' to 'frog'.
yq eval '.a[] | select(. == "apple") |= "frog"' sample.yml
Use select to filter data based on conditions, including boolean operators.
# Match with boolean operator 'or'.
yq eval '[.[] | select(.a == "cat" or .b == "dog")]' sample.yml
Yq v4 provides straightforward ways to aggregate data.
# Collect into array.
yq eval '[.a, .b]' sample.yml
# Collect into object.
yq eval '{"replicas": .spec.replicas}' sample.yml
# Splat into multiple objects.
yq eval '{"name": .pets[]}' sample.yml
You can generate new YAML content using --null-input.
# Create yaml from scratch.
yq eval --null-input '{"wrap": "frog"}'
Remove specific keys or array elements.
# Delete an entry.
yq eval 'del(.b)' sample.yml
# Delete an entry by index in an array.
yq eval 'del(.[1])' sample.yml
Yq v4 handles files containing multiple YAML documents.
# Retrieve a document index from a multiple-document yaml file.
yq eval '.a | documentIndex' sample.yml
# Filter/select a document by index.
yq eval 'select(. | documentIndex == 1)' sample.yml
Merge objects efficiently using the merge operator.
# Merge objects with '*'.
yq eval '.a * .b' sample.yml
Traverse all nodes in a YAML structure, optionally modifying them.
# Traverse all nodes recursively.
yq eval '..' sample.yml
# Traverse and change style to single quote.
yq eval '.. style="single"' sample.yml
Explore additional functionalities for enhanced YAML processing.
Enable shell completion for yq commands.
yq shell-completion
Process multiple YAML files simultaneously.
# Evaluate multiple files
yq eval-all ".metadata.name" a.yaml b.yaml