Yq v4 - Command-Line YAML Processor
Yq is a lightweight and portable command-line YAML processor. This page focuses on yq v4. For version 3, please use the yq
command.
Core Yq v4 Operations
Yq v4 allows for powerful manipulation of YAML data directly from your terminal. Below are common operations and examples.
Reading and Evaluating YAML
You can read specific nodes or evaluate expressions against YAML files.
# Read spec.template node from example.yml
yq eval '.spec.template' example.yml
Assigning and Updating Values
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
Filtering and Selecting Data
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
Collecting Data into Arrays and Objects
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
Creating YAML from Scratch
You can generate new YAML content using --null-input
.
# Create yaml from scratch.
yq eval --null-input '{"wrap": "frog"}'
Deleting Entries
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
Working with Multi-Document YAML
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
Merging Objects
Merge objects efficiently using the merge operator.
# Merge objects with '*'.
yq eval '.a * .b' sample.yml
Recursive Traversal
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
Advanced Yq v4 Features
Explore additional functionalities for enhanced YAML processing.
Shell Completion
Enable shell completion for yq commands.
yq shell-completion
Evaluating Multiple Files
Process multiple YAML files simultaneously.
# Evaluate multiple files
yq eval-all ".metadata.name" a.yaml b.yaml