One-Liner: Fun with Multi-line Blocktext and –Split/.Split()

The title is an oxymoron: I’m going to show a one-liner on how to deal with multi-line blocktext.  To start with, I’m using ‘blocktext’ to mean:

$blocktext = @"
    This is an
    example using
    @" .. "@

which is known from Unix-dom as ‘heretext’ and what I simply call ‘multi-line strings, below.  Yeah,, that’s a mouthful.  blocktext encompasses both, and it’s shorter, so blocktext it is.

    $blocktext = "
    This is another
    example of blocktext
    without using @`"

What’s the difference?

- Heretext can use embedded quotes, while multi-line strings need to escape them, for quote characters/strings that match the start of the string.

- Multi-line strings can be nicely indented, while the heretext terminator (“@) must be the first character on the line.

The trick is how to convert blocktext into arrays of text.  For this magic, we use .Split().  We can use –Split, but I’ll show below why using the class member is better than using the PowerShell operator.  Specifically, the below works for both varieties of blocktext:

    $arrayFromBlocktext = "
    This is another
    example of blocktext
    without using @`"

This works because "`n" is PowerShell's way of escaping a linNfeed, and "`r" is their way of escaping a caRriage return.

Why .Split(“`n`r”) instead of –Split “`n`r”?  So we can make add some additional features, specifically, ignoring blank lines and comments:

    $arrayFromBlocktext = "
    This is another
    example of blocktext
    without using @`"
    ".Split("`n`r") -replace "`#.*", "$([char]0)" -replace "#.*" -replace "$([char]0", "#" -replace "^\s*" -replace "\s*$" |
    ?{ $_; }

All this means:

- Escape “`#” by temporarily converting it NULL, then nuking everything after unescaped “#”, and replace NULL back to “#”.

- Remove leading and trailing spaces.

- Remove blank lines.

This is SO much better than:

$arrayTheOldFashionedWay = @(
Comments (0)

Skip to main content