Ram Kumar
Ram Kumar

Reputation: 89

How to select required columns in csv file using powershell

I have a csv file with data looking like this.

Div,Date,HomeTeam,AwayTeam,FTHG,FTAG,FTR,HTHG,HTAG,HTR
I1,20/08/16,Juventus,Fiorentina,2,1,H,1,0,H
I1,20/08/16,Roma,Udinese,4,0,H,0,0,D
I1,21/08/16,Atalanta,Lazio,3,4,A,0,3,A
I1,21/08/16,Bologna,Crotone,1,0,H,0,0,D

I am trying to export first six columns like below to a new csv file.

Div,Date,HomeTeam,AwayTeam,FTHG,FTAG
I1,20/08/16,Juventus,Fiorentina,2,1
I1,20/08/16,Roma,Udinese,4,0
I1,21/08/16,Atalanta,Lazio,3,4
I1,21/08/16,Bologna,Crotone,1,0

I am using the following powershell command.

Import-Csv $infile -DeLimiter ","|
Select'Div','Date','HomeTeam','AwayTeam','FTHG','FTAG'| 
Export-Csv $trimfile -DeLimiter "," -NoTypeInformation

But my output csv file looks like this

"Div","Date","HomeTeam","AwayTeam","FTHG","FTAG"
"I1","20/08/16","Juventus","Fiorentina","2","1"
"I1","20/08/16","Roma","Udinese","4","0"
"I1","21/08/16","Atalanta","Lazio","3","4"
"I1","21/08/16","Bologna","Crotone","1","0"

The no.of columns are much higher in the actual file. Simplified it here. What am I doing wrong?

Upvotes: 0

Views: 6416

Answers (1)

Manu
Manu

Reputation: 1742

Try with this code :

Import-Csv $infile -DeLimiter "," | 
Select-Object 'Div','Date','HomeTeam','AwayTeam','FTHG','FTAG' | 
ConvertTo-Csv -NoTypeInformation | 
ForEach-Object { $_ -replace '"', ""} | 
Out-File $trimfile

Upvotes: 3

Related Questions