我有一个.csv文件与两种类型的行。第一个包含头信息。它总是以AB
开头。第二种类型包含内容。这个总是以CD
开头。每个标题行之后可以有多个内容行(总是至少一个)。它们属于一起,直到下一个标题行(再次从AB
开始)。
的例子:
header1; header2; header3; header4; header5; header6; header7
AB; 12345; AB123456789; 10.03.2021; GT; BC987654321; EUR
CD; 456789; 22.24; Text; SW;
AB; 12345; AB123456789; 10.03.2021; GT; BC987654322; EUR
CD; 354345; 85.45; Text; SW;
CD; 123556; 94.63; Text; SW;
CD; 354564; 12.34; Text; SW;
CD; 135344; 32.23; Text; SW;
AB; 12345; AB123456789; 10.03.2021; GT; BC987654323; EUR
CD; 354564; 12.34; Text; SW;
CD; 852143; 34.97; Text; SW;
如何使用PowerShell将此文件拆分为几个。csv文件-每个标题行(AB)一个。我想要的结果是
BC987654321.csv
header1; header2; header3; header4; header5; header6; header7
AB; 12345; AB123456789; 10.03.2021; GT; BC987654321; EUR
CD; 456789; 22.24; Text; SW;
BC987654322.csv
header1; header2; header3; header4; header5; header6; header7
AB; 12345; AB123456789; 10.03.2021; GT; BC987654322; EUR
CD; 354345; 85.45; Text; SW;
CD; 123556; 94.63; Text; SW;
CD; 354564; 12.34; Text; SW;
CD; 135344; 32.23; Text; SW;
和BC987654323.csv
header1; header2; header3; header4; header5; header6; header7
AB; 12345; AB123456789; 10.03.2021; GT; BC987654323; EUR
CD; 354564; 12.34; Text; SW;
CD; 852143; 34.97; Text; SW;
我根本不习惯PowerShell,所以我很感激一个对新手友好的解决方案。
提前谢谢你。
如果我理解正确的话,您希望在'header1'等于'AB'的每一行上拆分csv,然后使用'header6'下该行中的内容作为输出文件名。
$path = 'D:Test'
$fileIn = Join-Path -Path $path -ChildPath 'input.csv'
$fileOut = $null # will get a value in the loop
$splitValue = 'AB' # the header1 value that decides to start a new file
$csv = Import-Csv -Path $fileIn -Delimiter ';'
# get an array of the column headers
$allHeaders = $csv[0].PsObject.Properties.Name
foreach ($item in $csv) {
if ($item.header1 -eq $splitValue) {
# start a new file
$fileOut = Join-Path -Path $path -ChildPath ('{0}.csv' -f $item.header6)
# create the new csv file with the first row of data already in it
$item | Select-Object $allHeaders | Export-Csv -Path $fileOut -Delimiter ';' -NoTypeInformation
}
else {
# rows with header1 not 'AB' are added to that file
if ([string]::IsNullOrEmpty($fileOut)) {
Write-Warning "Could not find a starting row (header1 = '$splitValue') for the file"
}
else {
$item | Select-Object $allHeaders | Export-Csv -Path $fileOut -Delimiter ';' -Append
}
}
}
当然,更改路径以匹配您的环境。
输出:
BC987654321.csv
"header1";"header2";"header3";"header4";"header5";"header6";"header7"
"AB";"12345";"AB123456789";"10.03.2021";"GT";"BC987654321";"EUR"
"CD";"456789";"22.24";"Text";"SW";"";
BC987654322.csv
"header1";"header2";"header3";"header4";"header5";"header6";"header7"
"AB";"12345";"AB123456789";"10.03.2021";"GT";"BC987654322";"EUR"
"CD";"354345";"85.45";"Text";"SW";"";
"CD";"123556";"94.63";"Text";"SW";"";
"CD";"354564";"12.34";"Text";"SW";"";
"CD";"135344";"32.23";"Text";"SW";"";
BC987654323.csv
"header1";"header2";"header3";"header4";"header5";"header6";"header7"
"AB";"12345";"AB123456789";"10.03.2021";"GT";"BC987654323";"EUR"
"CD";"354564";"12.34";"Text";"SW";"";
"CD";"852143";"34.97";"Text";"SW";;