You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell逐行转换文本文件为CSV文件的问题求助

屏幕抓取文本转CSV格式问题

任务

将屏幕抓取的文本转换为可导入Excel的CSV文件

环境

  • Windows 11
  • Notepad
  • PowerShell ISE
  • PowerShell v5.1

文本格式

  • 每条记录以7行重复模式呈现,最后一行含唯一关键词INDEX
  • 记录间空行数量不固定
  • 每行以CR LF结尾(经Scite验证)

预期输出

将每组7行内容合并为一行,以逗号分隔

问题

已编写匹配关键词的脚本,但无法将换行符替换为逗号,输出仍为原格式;使用Get-Content方法无法正确匹配关键词,求助解决转换问题。


输入示例

28
--
123.123.123.123 - fgh1
00:00:00:00:00:00
someword
 anotherword
INDEX word: 11


29
--
123.123.123.124 - fgh1
00:00:00:00:00:00
someword "INDEX
 anotherword
INDEX word: 11

预期输出

28,--,123.123.123.123 - fgh1,00:00:00:00:00:00,someword, anotherword,INDEX word: 11
29,--,123.123.123.124 - fgh1,00:00:00:00:00:00,someword, anotherword,INDEX word: 11

尝试的匹配脚本

foreach($line in [System.IO.File]::ReadLines(C:\InFile.txt))
{
 If ($line -match "INDEX") {Write-Host "Line contains INDEX"}
 ElseIf ($line -notmatch "INDEX") {Write-Host "Line does not contain INDEX"}
 }

转换脚本(未达到预期)

foreach($line in [System.IO.File]::ReadLines(C:\InFile.txt))
{
 If ($line -match "INDEX") {Out-File -append -FilePath C:\OutFile.txt -inputobject $line}
 ElseIf ($line -notmatch "INDEX") {Out-File -append -filepath C:\OutFile.txt -inputobject ($line -replace '\r?\n',',')}
 }

注:使用[System.IO.File]::ReadLines的原因

用Get-Content无法正确匹配关键词,尝试的代码:

$FilePath = "C:Infile.txt"
$FileContents = Get-Content -Path $FilePath -Raw | Out-String #Tried with or without "Out-String"
ForEach ($Line in $FileContents){
If ($Line -match "INDEX") {Write-Host "Line contains INDEX"}
ElseIf ($line -notmatch "INDEX") {Write-Host "Line does not contain INDEX"}
 }

解决方案

方法1:按记录分组处理

利用记录以7行一组且最后一行含INDEX的特点,逐行读取并缓存,每凑够7行就合并为CSV行输出:

$inputPath = "C:\InFile.txt"
$outputPath = "C:\OutFile.txt"
$recordBuffer = @()

foreach ($line in [System.IO.File]::ReadLines($inputPath)) {
    # 跳过空行
    if ([string]::IsNullOrWhiteSpace($line)) {
        continue
    }
    $recordBuffer += $line.TrimEnd("`r`n")
    # 当缓存到7行时,合并输出并清空缓存
    if ($recordBuffer.Count -eq 7) {
        $csvLine = $recordBuffer -join ','
        Add-Content -Path $outputPath -Value $csvLine
        $recordBuffer = @()
    }
}

方法2:使用Get-Content读取后分组

修正Get-Content的使用方式,先过滤空行再按7行分组:

$inputPath = "C:\InFile.txt"
$outputPath = "C:\OutFile.txt"

# 读取所有非空行
$lines = Get-Content -Path $inputPath | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }

# 按每7行分组处理
for ($i=0; $i -lt $lines.Count; $i+=7) {
    $record = $lines[$i..($i+6)]
    $csvLine = $record -join ','
    Add-Content -Path $outputPath -Value $csvLine
}

关键问题说明

  1. 原转换脚本的问题:[System.IO.File]::ReadLines读取的是单条行,行内没有\r\n,所以替换换行符无效;且每次Out-File -append都会自动添加换行,导致无法合并行。
  2. Get-Content原代码的问题:使用-Raw后会把整个文件读成单个字符串,ForEach ($Line in $FileContents)会逐个字符遍历,而非逐行,所以匹配逻辑错误。去掉-Raw即可正常逐行读取。

内容的提问来源于stack exchange,提问作者RASmith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 10:12:51