How can I get the number of bytes in a newline from PowerShell?

520 Views Asked by At

DOS/Windows newline is two (2) bytes, 0x0D0A. UNIX/Linux newline is one (1) byte, 0x0A. Mac newline is one (1) byte, 0x0D.

How can I write code to find the length of a newline on each platform? Output on Windows will produce two (2) bytes, but output on Linux will produce one (1) byte. I did not find anything related to this in about_Special_Characters.

On Windows:

PS C:\src\t> type .\nl.ps1
'`n'
'`n'.Length
"`n"
"`n".Length

Both Windows and Linux return the same result.

PS C:\src\t> .\nl.ps1
`n
2


1
1

There are 1 best solutions below

0
On BEST ANSWER

.NET Standard has an API for that, and is a always available from Powershell:

[system.environment]::newline.length

On Windows

PS> [system.environment]::newline.length
2

On Ubuntu

PS> [system.environment]::newline.length      
1