2015-11-15 31 views
-1

如何将csv拆分为折叠?我有一个csv说10行。我想分成5组,每组有2个文件。第一个文件有2行。第二文件具有剩余8.将csv分为定期间隔

下一组将具有3,3和4,4在1个文件,并残留在另一个文件等

id1,id2 
1,1 
2,2 
3,3 
4,4 
5,5 
6,6 
7,7 
8,8 
9,9 
10,10 

我希望的输出:

Set-1-A 
    1,1 
    2,2 

Set-1-B 
    3,3 
    4,4 
    5,5 
    6,6 
    7,7 
    8,8 
    9,9 
    10,10 

Set-2-A 
    3,3 
    4,4 

Set-2-B 
    1,1 
    2,2 
    5,5 
    6,6 
    7,7 
    8,8 
    9,9 
    10,10 

等..

+4

我仍然感到困惑,你如何提出对这些分裂。更明确。 – SomethingDark

+3

请包含确切的输入文件和所需的输出。 – vonPryz

+0

你想在这里使用什么语言....批处理或PowerShell?你有没有尝试过?很高兴看到_something_,所以我们可以帮助你改进它。 – Matt

回答

1

你可以使用一个嵌套循环抓住从CSV和出口n资料转移到新的文件:

$Data = Import-Csv .\input.csv 
$n = 2 
$SliceCount = 1 

while($Data) 
{ 
    $Slice = @() 
    for($i = 0; $i -lt $n; $i++){ 
     # shift rows from the input array, one by one 
     $Piece,$Data = $Data 
     $Slice += $Piece 
    } 

    # export each slice to a new csv file 
    $Slice | Export-Csv -Path (Join-Path $PWD "output_$($SliceCount).csv") -NoTypeInformation 
    $SliceCount++ 
} 
+0

这非常干净! – sodawillow

1

编辑代码修改答复意见

@echo off 
setlocal EnableDelayedExpansion 

for /F %%a in ('find /C /V "" ^< input.txt') do set "lines=%%a" 
set /P "sets=There are %lines% lines, enter number of sets: " 
set /A linesPerSet=lines/sets 
del set*-?.csv 2> NUL 

rem Initialize the indicators of all sets 
for /L %%s in (1,1,%sets%) do set "set[%%s]=1" 

rem Activate the first set 
set "set=1" 
set "set[1]=0" 

set "line=0" 
for /F "delims=" %%a in (input.txt) do (

    rem Check all sets and distribute the lines accordingly 
    for /L %%s in (1,1,%sets%) do if !set[%%s]! equ 0 (
     rem Output this line to first file of this set 
     >> set%%s-A.csv echo %%a 
    ) else (
     rem Output this line to second file of this set 
     >> set%%s-B.csv echo %%a 
    ) 

    rem Check if the first file of the set must change 
    set /A line+=1, lineMODlinesPerSet=line%%linesPerSet 
    if !lineMODlinesPerSet! equ 0 (
     rem Change the first file of set 
     set /A set+=1 
     for /L %%s in (1,1,!sets!) do set /A set[%%s]=set-%%s 
    ) 

) 

输出:

C:\> test.bat 
There are 10 lines, enter number of sets: 5 

C:\> type set*.csv 

set1-A.csv 

1,1 
2,2 

set1-B.csv 

3,3 
4,4 
5,5 
6,6 
7,7 
8,8 
9,9 
10,10 


set2-A.csv 

3,3 
4,4 

set2-B.csv 

1,1 
2,2 
5,5 
6,6 
7,7 
8,8 
9,9 
10,10 


set3-A.csv 

5,5 
6,6 

set3-B.csv 

1,1 
2,2 
3,3 
4,4 
7,7 
8,8 
9,9 
10,10 


set4-A.csv 

7,7 
8,8 

set4-B.csv 

1,1 
2,2 
3,3 
4,4 
5,5 
6,6 
9,9 
10,10 


set5-A.csv 

9,9 
10,10 

set5-B.csv 

1,1 
2,2 
3,3 
4,4 
5,5 
6,6 
7,7 
8,8 
+0

我需要类似的东西。但set1中的行应始终为2,set2中的行应始终为8. – mhn

+0

set B应始终保留所有未设置的行A – sodawillow

+0

代码已修复,请参阅编辑。从一开始你的描述应该更清晰。 – Aacini