powershell - 将固定宽度的 txt 文件转换为 CSV/set-content 或 out-file -append?

标签 powershell csv foreach fixed-width

输入文件是固定宽度的 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 构建一个行数组,要么使用写出 -为每次迭代追加。有没有更有效的方法来做到这一点?

最佳答案

Set-Content 通过一些小的调整应该可以正常工作。这是它应该如何工作的示例(这是外部 foreach 循环中的所有内容):

$csvFile = $file.BaseName
    if (!(get-childitem ./ |where-object {$_.Name -like $csvFile})) #check whether file has been processed
    { 
        (gc $file | foreach {
                $_.Insert($columBreaks[0],",").Insert($columBreaks[1],",").Insert($columBreaks[2],",").`
                Insert($columBreaks[3],",").Insert($columBreaks[4],",").Insert($columBreaks[5],",").`
                Insert($columBreaks[6],",").Insert($columBreaks[7],",").Insert($columBreaks[8],",").`
                Insert($columBreaks[9],",").Insert($columBreaks[10],",")
            }) | set-content $csvFile #note parenthesis around everything that gets piped to set-content
    }

顺便说一句,您可以使用 $file.BaseName 获取不带扩展名的文件名,而不是在“.”上拆分文件名:

$csvFile = $file.BaseName + ".csv"

关于powershell - 将固定宽度的 txt 文件转换为 CSV/set-content 或 out-file -append?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39897926/

相关文章:

javascript - 包含 FOREACH 可连接内容的表

string - 在Powershell中迭代字符串的通用列表(Lync聊天室成员)

Powershell Get-ChildItem -Filter 与具有相同值的 Where 子句的操作不同

r - 如何在R中将 block 组数据保存为文本格式?

sql - 将查询结果导出到 SQL Server 中的 CSV 文件问题

c# - C#foreach问题

string - 测试 PowerShell 字符串相等性

azure - 如何在powershell/azure cli中动态循环键值对

php - 在构建 MySql INSERT 中使用 PHP 变量

c# - Foreach 带有方括号中的 select/from?