Changes last name, first name to first name, last name in last column CSV powershell

≯℡__Kan透↙ 提交于 2020-01-05 10:30:29

问题


I am a newbie to powershell. I was trying to change last name, first name to first name, last name in the last column in CSV file and export all of the changes I have made to a new csv file.

The data looks like this.

Sport, Gender, Zip, Recruiter
"Baseball","Male", "12345", "John, Wayne"

I tried using

Get-Content "C:\import.csv" |    
ForEach-Object {$_.Recruiter -replace ",", ""} |      
ForEach-Object {$_.Sport -replace ",", ""} |     
Set-content "C:\export.csv"  

This is a sample code, which, of course, doesn't work, but I have to change a bunch of punctuation to each column using ForEach-Object and want the last column "F_name L_name". When I used $_.Recruiter to call the column, I got only empty csv file. When I used Import-csv instead of Get-content, I got only the column selected and all other columns are lost. Any help would be very appreciated.

Thank you.


回答1:


I think you were right to use Import-Csv for this task. It's much easier to work with these fields as object properties than it is to try to parse them as strings. Try this out.

Import-Csv "import.csv" | 
foreach { 
    $_.Recruiter = "{1}, {0}" -f ($_.Recruiter -split ', ')
    $_ 
} |
Export-Csv "export.csv"

The first line in the foreach splits the firstname/lastname in the Recruiter field, reverses them, and puts them back into the object. The second line in the foreach simply puts the whole object (including the fields that you didn't touch) back into the pipeline.



来源:https://stackoverflow.com/questions/28245618/changes-last-name-first-name-to-first-name-last-name-in-last-column-csv-powers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!