I have a text file like this:
File: sample1.txt
foo: {0}
bar: {1}
Hello {2}
I run the following commands:
$txt = gc Sample1.txt
$txt -f "bar","foo","world"
I got the output:
foo: bar bar: foo Hello world
Where did all the line breaks go?
Get-Content automically breaks the file into an array by lines. Use the -Raw flag to keep it as single string:
$txt = gc Sample1.txt -Raw
$txt -f "bar","foo","world"
If you are stuck on PowerShell 2, the Raw parameter doesn't exist. You need to use the .NET File API:
$txt = [IO.File]::ReadAllText($(Convert-Path Sample1.txt))
$txt -f "bar","foo","world"
I've used Convert-Path
because the .NET File API will default to resolving paths relative to the process's current directory, which is not the same as the current location in the path provider.
You can also use the $OFS automatic variable to control the Output Field Separator. In your example, the output field separator is a space, which is the default value for $OFS. You can see that space if you look closely at your output.
If you set $OFS to new line, as follows:
$OFS = "`n"
Your output should have the line breaks in it. This variable is useful in some other circumstances as well.
gc returns a String Array without any returns. You need to specify the return with `n .
PS:> "foo: {0}`nbar: {1}`nHello {2}" -f "bar","foo","world"
foo: bar
bar: foo
Hello world
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.