Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell读取csv文件,重新格式化为多行,写入csv文件_Powershell - Fatal编程技术网

Powershell读取csv文件,重新格式化为多行,写入csv文件

Powershell读取csv文件,重新格式化为多行,写入csv文件,powershell,Powershell,powershell非常新。我想创建一个powershell脚本,用于读取csv文件,其中的行如下所示: 6120137650,6/22/2020,,304066,267.98,,6/26/2020 6120208098,6/22/2020,,304329,230.54,,6/26/2020 $inputFile = 'D:\Test\input.csv' $outputFile = 'D:\Test\output.txt' Get-Content -Path $inputFile | F

powershell非常新。我想创建一个powershell脚本,用于读取csv文件,其中的行如下所示:

6120137650,6/22/2020,,304066,267.98,,6/26/2020
6120208098,6/22/2020,,304329,230.54,,6/26/2020
$inputFile  = 'D:\Test\input.csv'
$outputFile = 'D:\Test\output.txt'

Get-Content -Path $inputFile | ForEach-Object {
    # output the original line with '*,CHR00,' prepended
    "*,CHR00,$_"
    $fields = $_ -split ','

    # output second line
    $num = -[double]$fields[4]
    'CHR00,{0},2001-00,P,{1}' -f $fields[0], $num.ToString("F2", [CultureInfo]::InvariantCulture)

    # output third line
    'CHR00,{0},FRT OUT,R,{1}' -f $fields[0], $fields[4]
} | Set-Content -Path $outputFile
然后创建一个新的csv文件,每个输入行有三行,如下所示。任何添加到输入中没有的行的内容都是常量

*,CHR00,6120137650,6/22/2020,,304066,30,267.98,,6/26/2020
CHR00,6120137650,2001-00,P,-267.98
CHR00,6120137650,FRT OUT,R,267.98
*,CHR00,6120208098,6/22/2020,,304329,30,230.54,,6/26/2020
CHR00,6120208098,2001-00,P,-230.54
CHR00,6120208098,FRT OUT,R,230.54
因此,对于每个输入行:

写一个输出行,添加*、CHR00,然后添加输入行中的所有内容。 写一个输出行,CHR00后跟输入行的字段1,后跟2001-00,后跟P,后跟输入行的字段5的字段负数。 写一个输出行,CHR00后跟输入行的字段1,FRT OUT后跟R,输入行的字段5。
因为您需要的输出文件不是真正的CSV文件,所以我认为在这种情况下,您可以简单地迭代输入文件中的行,然后输出新构造的行,如下所示:

6120137650,6/22/2020,,304066,267.98,,6/26/2020
6120208098,6/22/2020,,304329,230.54,,6/26/2020
$inputFile  = 'D:\Test\input.csv'
$outputFile = 'D:\Test\output.txt'

Get-Content -Path $inputFile | ForEach-Object {
    # output the original line with '*,CHR00,' prepended
    "*,CHR00,$_"
    $fields = $_ -split ','

    # output second line
    $num = -[double]$fields[4]
    'CHR00,{0},2001-00,P,{1}' -f $fields[0], $num.ToString("F2", [CultureInfo]::InvariantCulture)

    # output third line
    'CHR00,{0},FRT OUT,R,{1}' -f $fields[0], $fields[4]
} | Set-Content -Path $outputFile

-f是PowerShell

每列的标题是什么?所需的输出恐怕不是有效的CSV文件。您可能不知道这一点,但通常通过单击✓ 左边的图标。这将有助于其他有类似问题的人更容易找到答案,并有助于激励人们回答您的问题。我为延迟接受此答案表示歉意。它就像一个符咒!非常感谢。