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

时间:2016-10-06 13:55:29

标签: 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设置一系列行 - 内容,或者为每次迭代使用write-out -append。有没有更有效的方法来做到这一点?

3 个答案:

答案 0 :(得分:2)

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"

答案 1 :(得分:0)

这是工作代码。修正了一些错误。

CD 'C:\\FOLDERPATH\'
$filter = "FILE_NAME_*.txt" 

$columns = 11,22,32,42,54 

# DO NOT NEED TO REVERSE [array]::Reverse($columns) #too lazy to re-write array after finding out I need to iterate in reverse

$files = get-childitem ./ |where-object {$_.Name -like $filter}
$newDelimiter = '|'

foreach($file in $files)
{
    $file

    $csvFile = 'C:\\FOLDERPATH\NEW_' + $file.BaseName + '.txt'
    if (!(get-childitem ./ |where-object {$_.Name -like $csvFile})) #check whether file has been processed
    { 

        $content | ForEach {
            $line = $_
            $counter = 0
            $columns | ForEach {
                $line = $line.Insert($_+$counter, $newDelimiter)  
                $counter = $counter + 1
                }
            $line = $line.Trim($newDelimiter)
            $line
        } | set-content $csvFile
    }

} 

答案 2 :(得分:0)

我认为这很常见。这是一个实际的例子,将固定宽度的文件转换为对象。然后将其导出到csv很简单。这同样适用于转换旧式命令,例如netstat。

externals