52

Say I have the following string:

"abcdefghijklmnopqrstuvwxyz"

And I think its too long for one line in my YAML file, is there some way to split that over several lines?

>-
    abcdefghi
    jklmnopqr
    stuvwxyz

Would result in "abcdefghi jklmnopqr stuvwxyz" which is close, but it shouldn't have any spaces.

Jake
  • 581
  • 1
  • 5
  • 4

2 Answers2

50

Use double-quotes, and escape the newline:

"abcdefghi\
jklmnopqr\
stuvwxyz"
Jesse Beder
  • 31,716
  • 20
  • 105
  • 143
  • Single quotes also appear to work, and all indentation (even unequal indentation) appears to be stripped. Thanks! – quornian Apr 23 '14 at 21:36
  • 4
    i am using this for YAML in puppet "Hiera" and single quotes does not work, as they do not honor \ as an escape character in RUBY YAML at least. have not tested it with other YAML parsers. – Walid Jan 04 '15 at 10:17
  • See [this other StackOverflow answer](http://stackoverflow.com/questions/3790454/in-yaml-how-do-i-break-a-string-over-multiple-lines/21699210#21699210) for a good overview of all the different wrapping styles in YAML. – Christian Long May 09 '16 at 21:53
  • 2
    Single-quotes shouldn't behave like that. From the spec: `it is only possible to break a long single-quoted line where a space character is surrounded by non-spaces.` – Steve Bennett Dec 18 '16 at 23:53
  • for certain python API operation, using single quotes adds a space in the breakpoint of string, but double quotes works fine... thanks :) – flux0987 May 24 '21 at 11:49
19

There are some subtleties that Jesse's answer will miss.

YAML (like many programming languages) treats single and double quotes differently. Consider this document:

regexp: "\d{4}"

This will fail to parse with an error such as:

found unknown escape character while parsing a quoted scalar at line 1 column 9

Compare that to:

regexp: '\d{4}'

Which will parse correctly. In order to use backslash character inside double-quoted strings you would need to escape them, as in:

regexp: "\\d{4}"

I'd also like to highlight Steve's comment about single-quoted strings. Consider this document:

s1: "this\
  is\
  a\
  test"

s2: 'this\
  is\
  a\
  test'

When parsed, you will find that it is equivalent to:

s1: thisisatest
s2: "this\\ is\\ a\\ test"

This is a direct result of the fact that YAML treats single-quoted strings as literals, while double-quoted strings are subject to escape character expansion.

larsks
  • 228,688
  • 37
  • 348
  • 338