yq/pkg/yqlib/doc/operators/comment-operators.md

2.6 KiB

Comment Operators

Use these comment operators to set or retrieve comments.

Like the = and |= assign operators, the same syntax applies when updating comments:

plain form: =

This will assign the LHS nodes comments to the expression on the RHS. The RHS is run against the matching nodes in the pipeline

relative form: |=

Similar to the plain form, however the RHS evaluates against each matching LHS node! This is useful if you want to set the comments as a relative expression of the node, for instance its value or path.

{% hint style="warning" %} Note that versions prior to 4.18 require the 'eval/e' command to be specified.

yq e <exp> <file> {% endhint %}

Set line comment

Given a sample.yml file of:

a: cat

then

yq '.a line_comment="single"' sample.yml

will output

a: cat # single

Use update assign to perform relative updates

Given a sample.yml file of:

a: cat
b: dog

then

yq '.. line_comment |= .' sample.yml

will output

a: cat # cat
b: dog # dog

Set head comment

Given a sample.yml file of:

a: cat

then

yq '. head_comment="single"' sample.yml

will output

# single

a: cat

Set foot comment, using an expression

Given a sample.yml file of:

a: cat

then

yq '. foot_comment=.a' sample.yml

will output

a: cat

# cat

Remove comment

Given a sample.yml file of:

a: cat # comment
b: dog # leave this

then

yq '.a line_comment=""' sample.yml

will output

a: cat
b: dog # leave this

Remove (strip) all comments

Note the use of ... to ensure key nodes are included.

Given a sample.yml file of:

a: cat # comment
# great
b: # key comment

then

yq '... comments=""' sample.yml

will output

a: cat
b:

Get line comment

Given a sample.yml file of:

a: cat # meow

then

yq '.a | line_comment' sample.yml

will output

meow

Get head comment

Given a sample.yml file of:

# welcome!

a: cat # meow

# have a great day

then

yq '. | head_comment' sample.yml

will output

welcome!

Head comment with document split

Given a sample.yml file of:

# welcome!
---
# bob
a: cat # meow

# have a great day

then

yq 'head_comment' sample.yml

will output

welcome!
bob

Get foot comment

Given a sample.yml file of:

# welcome!

a: cat # meow

# have a great day
# no really

then

yq '. | foot_comment' sample.yml

will output

have a great day
no really