我有一个大的 (9 GiB)、ASCII 编码、管道分隔的文件,具有 UNIX 样式的行结尾; 0x0A。
我想将前 100 条记录采样到一个文件中进行调查。以下将产生 100 条记录(1 条标题记录和 99 条数据记录)。但是,它将行结尾更改为 DOS/Winodws 样式;回车换行,0x0D0A。
Get-Content -Path .\wellmed_hce_elig_20191223.txt |
Select-Object -first 100 |
Out-File -FilePath .\elig.txt -Encoding ascii
我了解 iconv、recode 和 dos2unix。这些程序不在我的系统上,并且不允许安装。我搜索并找到了很多关于如何到达 CRLF 的地方。我还没有找到任何关于到达或保持 LF 的信息。
如何生成以 LF 行结尾而不是 CRLF 结尾的文件?
最佳答案
补充Theo's helpful answer基于很少使用的 -ReadCount
进行性能优化参数:
Set-Content -NoNewLine -Encoding ascii .\outfile.txt -Value (
(Get-Content -First 100 -ReadCount 100 .\file.txt) -join "`n") + "`n"
)
-First 100
指示Get-Content
阅读(最多)100
行。-ReadCount 100
导致这 100 行被读取并以数组形式一起发出,从而加快读取和后续处理的速度。- 注意:在 PowerShell [Core] v7.0+ 中,您可以使用简写
-ReadCount 0
与-First <n>
结合意思是:读取请求的<n>
行作为单个数组;由于早期版本(包括 Windows PowerShell)中的错误,-ReadCount 0
始终读取整个文件,即使存在-First
(又名-TotalCount
又名-Head
)。
此外,即使从 PowerShell [Core] 7.0.0-rc.2(撰写本文时的当前版本)开始,组合-ReadCount 0
与-Last <n>
(又名-Tail
)应该避免(暂时):虽然生成的输出是正确的,但在幕后它又是读取的整个文件 ;请参阅this GitHub issue .
- 注意:在 PowerShell [Core] v7.0+ 中,您可以使用简写
请注意
+ "`n"
,这确保输出文件也将有一个尾随换行符(Unix世界中的文本文件应该有)。
虽然上述也适用于 -Last <n>
( -Tail <n>
) 从文件的末尾提取 Theo 的(较慢)Select-Object
由于可用参数 -Skip
,解决方案在提取任意范围的行方面提供了更大的灵活性。 , -SkipLast
,和-Index
;但是,也可以直接在 Get-Content
上提供这些参数。 this GitHub feature request 中提出了卓越的性能.
另请注意,我使用了 Set-Content
而不是Out-File
.
如果您知道自己正在编写文本,Set-Content
就足够了,而且通常更快(尽管在这种情况下,这并不重要,因为要写入的数据作为单个值传递)。 p>
全面概述 Set-Content
之间的差异和Out-File
/>
,参见this answer .
<强> Set-Content
与 Out-File
基准:
注意:此基准测试比较了两个 cmdlet 将通过管道接收的许多个输入字符串写入文件的情况。
# Sample array of 100,000 lines.
$arr = (, 'foooooooooooooooooooooo') * 1e5
# Time writing the array lines to a file, first with Set-Content, then
# with Out-File.
$file = [IO.Path]::GetTempFileName()
{ $arr | Set-Content -Encoding Ascii $file },
{ $arr | Out-File -Encoding Ascii $file } | % { (Measure-Command $_).TotalSeconds }
Remove-Item $file
使用 Windows PowerShell v5.1 的 Windows 10 VM 的示例计时(以秒为单位):
2.6637108 # Set-Content
5.1850954 # Out-File; took almost twice as long.
关于powershell - 如何保留 UNIX LF 行结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60157755/