I want to remove the quotation marks for only the first column of my csv file with powershell
So instead of:
"Username","Identifier"
"booker12","9012"
"grey07","2070"
I want the result to be:
Username,"Identifier"
booker12,"9012"
grey07,"2070
To remove all quotation marks the code would be
Import-Csv "test.csv" | ConvertTo-CSV -NoTypeInformation | % { $_ -Replace '"', ""} | Out-File C:\CSV_Tests\test.csv -fo -en ascii
But how to remove the marks just for the first column?
Thanks!
CodePudding user response:
As commented, it is recommended to install the latest PowerShell version which has an new ConvertTo-Csv
/Export-Csv
cmdlets with a -quotefields
.
But as that appears not to be possible for your environment:
$Csv = @'
"Username","Identifier"
"booker12","9012"
"grey07","2070"
'@ -Split '\r?\n'
$Csv -Replace '^"([^"]*)"', '$1'
Username,"Identifier"
booker12,"9012"
grey07,"2070"
Explanation:
- The first
^
marks the beginning of a line ([^"]*)
selects all successive characters that aren't double quotes- '$1' is the placeholder the results of the sequence defined in
2.
For your file this means:
(Get-Content .\Test.csv) -Replace '^"([^"]*)"', '$1' |Set-Content .\Test.csv
- Note that the parenthesis around
(Get-Content .\Test.csv)
are not recommended but required if you write back to the same file.