使用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
代码说明
- 定义固定内容:提前把硬编码行、表头、分隔线定义好,方便后续组合输出
- 读取并过滤文件内容:用
Select-Object -Skip 1跳过不需要的首行Processing... - 拆分每行数据:通过两次拆分(先
.后=)把原行拆分成对应三部分,加上固定的第一列内容 - 组合输出内容:把固定内容和处理后的行合并成完整的输出数组
- 写入文件:将结果写入指定路径的文件,指定UTF-8编码避免乱码
内容的提问来源于stack exchange,提问作者Intern99
相关产品推荐
相关产品推荐

