Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

Add multiple columns based on unique entries in other column in csv with powershell

I've done some basic work with powershell over the last year, but for some reason this is evading me. Any help would be appreciated.

I have a csv file that will have several hundred entries:

Path,Data,Files
\someserversomepath1,100,1
\someserversomepath2,150,4
\someserversomepath1,200,5
\someserversomepath3,450,8
\someserversomepath4,200,23
\someserversomepath1,350,2
\someserversomepath2,800,9

I'd like to have the powershell script parse through the file and produce a new csv with results that show the unique paths and summed data and files values. So from the above my expected results would be (preferrably sorted by largest data value):

Path,Data,Files
\someserversomepath2,950,9
\someserversomepath1,650,8
\someserversomepath3,450,8
\someserversomepath4,200,23

I've found several answers referring to summing a single column, but I haven't figured out it out for two columns yet. Any suggestions on both code and/or technique would be greatly appreciated. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ugly code ...

$csv=Import-Csv c:	emp	est.csv 
$csv | select -Unique -expand path|%{
    $path=$_
    $sdata=($csv | ?{$_.path -eq $path} | measure-object data -sum).sum
    $files=($csv | ?{$_.path -eq $path} |  Measure-Object files -sum).sum   
    "$path,$sdata,$files" |out-file c:	emp
ew.csv -append
}   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...