I need to sample the first N records of files which use UNIX-style (0x0A) newlines.
It is easy enough to use Get-Content -First 3
to get the first three (3) lines. However, when Out-File
writes them it uses Windows-style newlines.
How can I write the first N lines to a file using the newline style of the source file?
PS C:\src\t> Get-Content -Path .\filefile1.txt
123
456
789
012
345
PS C:\src\t> Format-Hex -Path .\filefile1.txt
Label: C:\src\t\filefile1.txt
Offset Bytes Ascii
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
------ ----------------------------------------------- -----
0000000000000000 31 32 33 0A 34 35 36 0A 37 38 39 0A 30 31 32 0A 123�456�789�012�
0000000000000010 33 34 35 0A 345�
A file produced through Out-File replaces the 0A newlines with 0D0A line endings.
PS C:\src\t> Get-Content -Path .\filefile1.txt -First 3 | Out-File -Path .\filefile2.txt -Encoding ascii
PS C:\src\t> Format-Hex -Path .\filefile2.txt
Label: C:\src\t\filefile2.txt
Offset Bytes Ascii
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
------ ----------------------------------------------- -----
0000000000000000 31 32 33 0D 0A 34 35 36 0D 0A 37 38 39 0D 0A 123��456��789��
Using the -NoNewline
switch removes -all- newlines.
PS C:\src\t> Get-Content -Path .\filefile1.txt | Out-File -FilePath .\filefile2.txt -Encoding ascii -NoNewline
PS C:\src\t> Format-Hex -Path .\filefile2.txt
Label: C:\src\t\filefile2.txt
Offset Bytes Ascii
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
------ ----------------------------------------------- -----
0000000000000000 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 123456789012345
PS C:\src\t> $PSVersionTable.PSVersion.ToString()
7.2.1