Skip to main content
0 reactions

How to Write a Multi-Line String in YAML with > (Folded Style)

Featured card for How to Write a Multi-Line String in YAML with the folded style: a shop.yml file whose note spreads over two lines, a yq command that reads .note and prints The shop opens at nine and closes at six., and the note Lines join with a space.
How to Write a Multi-Line String in YAML with > (Folded Style)

A > after a key lets you write a long string over several lines. YAML folds the lines into one, joined by spaces, so a long sentence stays easy to read in the file.

Every command and output on this page is real, run with yq 4.54.3 on macOS.

Syntax

SyntaxYAML
key: >
  first part of the text
  second part of the text
  • >: starts a folded block. The text begins on the next line.
  • The text lines, all indented by the same number of spaces under the key. YAML joins them with a space.
  • The end: the string ends with one line break, after the last line.

See Folded Style (opens in a new tab) in the YAML 1.2.2 specification.

Prerequisites

The Example

A shop’s opening-hours note, in a file named shop.yml.

Step 1: Write the YAML

shop.ymlYAML
note: >
  The shop opens at nine
  and closes at six.

Step 2: Read the String with yq

TerminalBash
yq '.note' shop.yml
OutputPlain text
The shop opens at nine and closes at six.

yq prints the two lines as one, joined by a space, followed by an empty line: the string ends with a line break.

Step 3: See the Exact Text

TerminalBash
yq -o=json '.' shop.yml
OutputPlain text
{
  "note": "The shop opens at nine and closes at six.\n"
}

-o=json prints the value as JSON, where \n shows the line break at the end.

Common Mistakes

MistakeWhat happensDo this instead
One line indented more than the firstThat line keeps its line break and its extra spaces: "note": "The shop opens at nine\n and closes at six.\n"Indent every line of the text by the same amount

FAQ

How do I drop the line break at the end?

Write >- instead of >. The same file then gives:

OutputPlain text
{
  "note": "The shop opens at nine and closes at six."
}

Conclusion

Write > after the key, indent the text lines below it by the same amount, and YAML joins them into one line that ends with a line break. Write >- to leave out that last line break.

Additional Resources

0 comments