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

使用PowerShell从含双分隔符的TXT文件提取列并生成CSV

PowerShell处理文本生成指定格式输出的解决方案

需求说明

现有sample.txt文件,内容如下:

Processing...
Cl.Cog="/u/l/Cg.txt"
V.DM=Nv
AL.Ft="He Se Fe",Bt,@L(Ey,0),&Ct:&Cu3

需要将其转换为指定格式的输出文件(output.csv),要求:

  • 首行硬编码为PHP> This is hard coded line;
  • 包含4列表头,表头下方有分隔线
  • 新增固定内容为abcdefg的第一列
  • 将原文件中除首行外的内容拆分后填入对应列:
    • 第二列取.前的部分
    • 第三列取.和=之间的部分
    • 第四列取=之后的全部内容

期望输出格式如下:

PHP> This is hard coded line;

column1              column2              column3              column4               
+-------------------+-------------------+-------------------+-------------------
abcdefg                Cl                 Cog               "/u/l/Cg.txt"               
abcdefg                V                  DM                   Nv
abcdefg                AL                 Ft                "He Se Fe",Bt,@L(Ey,0),&Ct:&Cu3

用户尝试的代码无法正常工作:

Get-Content test.txt | 
$headerString = "PHP> This is hard coded line;"

$headerElements = $headerString -split "\s+" | Where-Object{$_}
$headerIndexes = $headerElements | ForEach-Object{$headerString.IndexOf($_)}
$results = $data 
Foreach {"$((_ -split '\s+',4)[0..2])"} |
Out-file -filepath "D:\output.txt"    

可行PowerShell代码

# 定义硬编码首行、表头和分隔线
$hardcodedLine = "PHP> This is hard coded line;"
$header = "column1              column2              column3              column4"
$separator = "+-------------------+-------------------+-------------------+-------------------"

# 读取sample.txt,跳过第一行"Processing..."
$lines = Get-Content -Path "sample.txt" | Select-Object -Skip 1

# 处理每一行数据,生成对应行内容
$outputLines = $lines | ForEach-Object {
    # 拆分当前行:先按第一个"."拆分,再按第一个"="拆分
    $part1, $rest = $_ -split "\.", 2
    $part2, $part3 = $rest -split "=", 2
    # 格式化输出行,用空格填充对齐列
    "abcdefg                $part1                 $part2                $part3"
}

# 组合所有输出内容
$fullOutput = @(
    $hardcodedLine,
    "",
    $header,
    $separator
) + $outputLines

# 写入到output.csv文件
$fullOutput | Out-File -FilePath "D:\output.csv" -Encoding utf8

代码说明

  1. 定义固定内容:提前把硬编码行、表头、分隔线定义好,方便后续组合输出
  2. 读取并过滤文件内容:用Select-Object -Skip 1跳过不需要的首行Processing...
  3. 拆分每行数据:通过两次拆分(先.后=)把原行拆分成对应三部分,加上固定的第一列内容
  4. 组合输出内容:把固定内容和处理后的行合并成完整的输出数组
  5. 写入文件:将结果写入指定路径的文件,指定UTF-8编码避免乱码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:53:13