【发布时间】:2017-02-15 07:30:30
【问题描述】:
输入文件是一个固定宽度的 txt 文件。我的客户通常在 Excel 中打开它并手动指定分栏符。我希望用逗号替换某些空格,以便我可以解析为 CSV 并保存为 XLS 或其他格式。
$columBreaks = 20, 35, 50, 80, 100, 111, 131, 158, 161, 167, 183
[array]::Reverse($columBreaks) #too lazy to re-write array after finding out I need to iterate in reverse
$files = get-childitem ./ |where-object {$_.Name -like "FileFormat*.txt"}
foreach($file in $files)
{
$name = $file.Name.split(".")
$csvFile = $name[0]+".csv"
if (!(get-childitem ./ |where-object {$_.Name -like $csvFile})) #check whether file has been processed
{
$text = (gc $file)
foreach ($line in $text)
{
foreach ($pos in $columBreaks)
{
#$line.Substring($char-1,3).replace(" ", ",")
$line = $line.Insert($pos,",")
#out-file -append?
}
}
}
#set-content?
}
那么写出这些内容的最有效方法是什么?我曾希望使用 set-content,但我认为这是不可能的,因为我们正在逐行处理,所以我认为我要么必须为 set-content 构建一组行,要么使用 write-out -为每次迭代追加。有没有更有效的方法来做到这一点?
【问题讨论】:
标签: powershell csv foreach fixed-width