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

StackOverflow https://stackoverflow.com/questions/21902966

  •  14-10-2022
  •  | 
  •  

Pregunta

"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.

¿Fue útil?

Solución

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.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top