2012-11-29 72 views
2

我是PowerShell的新手,但这看起来是做这个任务的最佳工具。 有一个CSV文件看起来像这样:按列使用Powershell拆分csv文件

Date,mary1,mary2,maryr3,mary4 
9/01/2011 1:00,1.39,3.43,3.29,1.83 
9/01/2011 3:00,0,0,0,0 
9/01/2011 4:00,0,0,0,0 
9/01/2011 5:00,0,0,0,0 
9/01/2011 6:00,1.91,0.07,0.09,0.09 
9/01/2011 7:00,5.57,2.01,2.11,3.4 
9/01/2011 8:00,0.53,0.41,0.35,2.01 
9/01/2011 9:00,4.72,0.15,0.21,3.15 
9/01/2011 10:00,0.21,0,0.49,0.72 
9/01/2011 11:00,2.44,0.77,2.06,1.7 
9/01/2011 12:00,0,4.91,5.21,1.98 

这是逗号分隔。 我想分解成多个文本文件包含一列,基于标题列。

实际上我会有多个列,所以我想要一个更通用的代码来处理更多的行和列。

对此有何看法?我能够使用拆分功能,并获得单个列,但我的PowerShell的知识,但不允许我做多个提取。

任何帮助将不胜感激。

回答

1

尝试:

$a = Import-Csv .\myfile.csv 
$b = $a[0] | Get-Member | ? { $_.membertype -eq 'noteproperty'} | select name 
$b | % { $a | ft -Property $_.name | out-file "$($_.name).txt" } 
+0

这很好。谢谢 – Mary

+0

很高兴帮助! –

0

查找Import-CSV或按行处理文件。要逐行读取文件,请使用.Net Framework。按逗号分隔每行,并根据数组索引添加所需列以输出文件。注意行式处理:如果源数据中有逗号,这将会突然崩溃。像这样,

# Open the source file 
$file = [IO.File]::OpenText("somefile.csv") 
# Read each line 
while($line = $file.ReadLine()) { 
    # Split line data on comma 
    $l= $line.Split(',') 
    # Add columns 0 and 2 other file 1 
    add-content "otherfile1.csv" $("{0},{1}" -f $l[0], $l[2]) 
    # Add columns 1, 3 and 5 other file 2 
    add-content "otherfile2.csv" $("{0},{1},{2}" -f $l[1], $l[3], $l[5]) 
} 
+0

非常感谢,我现在试试这个,送还给你。 – Mary

+0

非常感谢,这对于将它分成两个文件非常有效,但是我想知道如何循环它以一次提取一列并给我总共5个(或n个)文件? – Mary

0
###import csv file with value 

$ps1 = Import-Csv .\testps.csv 
    foreach($p in $ps1){ 

## value which will be seprated 

$t = $p.test 
#####split delimiter is space you can select your own like ,/etc. 
$t1 = $t.Split(" ") 
##########first value 
    $test1 = $t1[0] 
######second value 
    $test2 = $t1[1] 
    #####Adding value in csv file test1 and test2 
    echo $p | Select-Object *,@{n='test1';e={"$test1"}},@{n='test2';e= {"$test2"}}|Export-Csv -Append testdone.csv 

}