powershell - Powershell:Get-Content 的 ForEach 行读取是否返回 EOF ..?
问题描述
读取任意大小的随机 HTML 输入文件我限制读取最多 1000 行或结束 /html 标记。工作正常。
问题出在小文件和 /html 标签丢失时。我想知道什么时候结束。
问题:是否有某种类型的 EOF 属性……?
$fileContents = (Get-Content -LiteralPath $filePath -totalcount 999)
ForEach ($line in $fileContents){
$LineNo = $LineNo +1;
if ((($line.ToLower().StartsWith("</html>"))) -or ($LineNo -gt 999) -or ??? END_OF_$fileContents ???)
{
# Do the rest of the processing in here...
}
}
几天后,这是我处理这个问题的最终代码(向右滚动);
$fileContents = (Get-Content -LiteralPath $filePath -totalcount 999)
ForEach ($line in $fileContents){
$LineNo = $LineNo +1;
if ((($line.ToLower().StartsWith("</html>"))) -or ($LineNo -gt 500) -or ($LineNo -ge $fileContents.Count))
{
# Do the rest of the processing in here...
}
}
这样做的想法是“摆脱”处理大量 html 文件,但仍然能够处理少量文件,即使它们的格式不正确(在电子邮件文件中很常见)。
解决方案
无需额外的 EOF 文件检查。我们将用于Get-Content
处理 EOF 检查以及行数(999 行)检查。
然后我们可以使用正则表达式来解析文件以找到关闭的 HTML 标记和行号。
$fileContents = (Get-Content -LiteralPath $filePath -TotalCount 999)
$result = $fileContents | Select-String '<\/html>'
if($result -ne $null -or $fileContents.Count -eq 999)
{
# Hit Close HTML Tag or file is bigger than 1000 lines
Write-Host "Hit close tag at line: $($result.LineNumber) or EOF"
# Do the rest of the processing in here...
}
推荐阅读
- prolog - Prolog 谓词在奇数位置打印项目。帮我写代码?
- java - PdfBox renderImageWithDpi 中的形状点不正确
- c++ - 多个 If 语句与使用逻辑运算符评估条件的单个语句
- firebase - 如何从终端获取 SHA 1 指纹证书?(没有“安卓工作室”)
- python - 复制性能:列表与数组
- c# - 在代码隐藏中重新分配 StaticResource 的值
- java - 安卓自动拍照
- azure-pipelines - Azure Build Pipeline - 使用多个作业构建的多个存储库 - 如何重用每个构建的相同工作目录?
- python - 在基于类的视图上找不到页面 (404)
- python - 如何通过 SymPy 中的给定子表达式自动简化表达式