Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve newlines when using variables in here-strings

Tags:

powershell

When running the following code:

  $txt = Get-Content file1.txt

    $a = @"
     -- file start --
     $txt
     -- file end --
    "@

   $a

All new lines are removed from the file's contents, but just running

$txt

prints out the file without stripping the new lines.

Any idea how to get it to work as desired using the here-string?

Thanks!

like image 915
Bob Smith Avatar asked Oct 25 '12 18:10

Bob Smith


People also ask

How do you preserve newlines in HTML?

Preserve Newlines, Line Breaks, and Whitespace in HTML Use the white-space: pre; setting to display long-form content containing whitespace and line breaks the same way as provided by a user. The text will also stay inside the container boundaries and now overflow the parent: <span style="white-space: pre;"> This is a long-form text.

Can you put newlines in PowerShell string?

Once you have created this here-string enclosure, you are free to add newlines, symbols, and text formatting, with no restriction on the amount of text written. PowerShell uses the .NET System.String type, which represents text as a sequence of UTF-16 code units.

Why can't I see the newline in my $temp string?

By default, the IFS is set to whitespace (spaces, tabs, and newlines), so the shell chops your $TEMP string into arguments and it never gets to see the newline, because the shell considers it a separator, just like a space. Show activity on this post. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.

Why can't I see the newline in a string in IFS?

By default, the IFS is set to whitespace (spaces, tabs, and newlines), so the shell chops your $TEMP string into arguments and it never gets to see the newline, because the shell considers it a separator, just like a space. Show activity on this post. Thanks for contributing an answer to Stack Overflow!


2 Answers

If you put an array in a string it will be expanded with $OFS (or a space if $OFS is $null) between the items. You can see the same effect with either

"$txt"
''+$txt

and a few others. You can set $OFS="`r`n" which would change the space with which they are joined to a line break.

You could also change the Get-Content at the start to either

$txt = Get-Content file1.txt | Out-String
$txt = [IO.File]::ReadAllText((Join-Path $pwd file1.txt))
like image 188
Joey Avatar answered Oct 25 '22 08:10

Joey


Pipe $txt to Out-String inside a sub-expression.

$a = @"
    -- file start --
    $($txt | Out-String)
    -- file end --
"@
like image 42
Shay Levy Avatar answered Oct 25 '22 09:10

Shay Levy