Zombo
Zombo

Reputation: 1

Out-File and carriage returns

If I have a program, for example this Go program:

package main
import "fmt"

func main() {
   fmt.Print("North East\n")
   fmt.Print("South West\n")
}

This program produces no carriage returns at all, only newlines. However if I do this:

prog.exe > prog.txt

PowerShell takes it upon itself to add carriage returns to every line. I only want PowerShell to faithfully output what my program created, nothing more. So I tried this instead:

prog.exe | Out-File -NoNewline prog.txt

and PowerShell didn't add carriage returns, but it went ahead and removed the newlines too. How do I do what I am trying to do? Update: based on an answer, this seems to do it:

start -rso prog.txt prog.exe

Upvotes: 3

Views: 3987

Answers (2)

js2010
js2010

Reputation: 27606

This works for me. Note that out-file defaults to utf16 encoding, vs set-content.

"hi`nthere`n" | out-file file -NoNewline

format-hex file


           Path: C:\users\admin\foo\file

           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   FF FE 68 00 69 00 0A 00 74 00 68 00 65 00 72 00  .þh.i...t.h.e.r.
00000010   65 00 0A 00                                      e...

Ok, my first Go program:

(go run .) -join "`n" | set-content file -NoNewline

The problem is windows programs output carriage return and linefeed. This would work fine, or no carriage return would work in linux or osx powershell.

package main
import "fmt"

func main() {
   fmt.Print("North East\r\n")
   fmt.Print("South West\r\n")
}
go run . > file

Actually this problem is resolved in powershell 7. The file will end up having \r\n even if the go code doesn't.

Upvotes: 0

marsze
marsze

Reputation: 17154

It seems this is due to the behavior of redirecting output. It's split up into separate lines wherever a newline is detected, but when Powershell joins the lines again, it will use both newline and carriage return (the Windows default).

This should not be an issue though, if you redirect the output directly. So this should give you the expected behavior:

Start-Process prog.exe -RedirectStandardOutput prog.txt

Upvotes: 2

Related Questions