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!
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.
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.
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.
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!
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))
Pipe $txt to Out-String inside a sub-expression.
$a = @"
-- file start --
$($txt | Out-String)
-- file end --
"@
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With