Site icon JD Bots

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

Syntax

key: >
  first part of the text
  second part of the text

See Folded Style 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.yml

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

Step 2: Read the String with yq

Terminal

yq '.note' shop.yml

Output

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

Terminal

yq -o=json '.' shop.yml

Output

{
  "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:

Output

{
  "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

Exit mobile version