How to remove double quotes on specific column from CSV file using Powershell script

吃可爱长大的小学妹 提交于 2019-12-11 06:27:24

问题


"ID","Full Name","Age"

"1","Jone Micale","25"

Here a sample from a CSV file that I created, and now I want to remove double quotes from only the ID and Age column value.

I tried different ways but I don't want to create a new file out of it. I just want to update the file with changes using PowerShell v1.


回答1:


Export-Csv will always put all fields in double quotes, so you have to remove the undesired quotes the hard way. Something like this might work:

$csv = 'C:\path\to\your.csv'
(Get-Content $csv) -replace '^"(.*?)",(.*?),"(.*?)"$', '$1,$2,$3' |
    Set-Content $csv

Regular expression breakdown:

  • ^ and $ match the beginning and end of a string respectively (Get-Content returns an array with the lines from the file).
  • "(.*?)" matches text between two double quotes and captures the match (without the double quotes) in a group.
  • ,(.*?), matches text between two commas and captures the match (including double quotes) in a group.
  • $1,$2,$3 replaces a matching string with the comma-separated first, second and third group from the match.


来源:https://stackoverflow.com/questions/21902966/how-to-remove-double-quotes-on-specific-column-from-csv-file-using-powershell-sc

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