0

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!

user18209625
  • 139
  • 2
  • 15
  • The `-NoTypeInformation` parameter suggest that you using an old version of PowerShell. I recommend you install the [latest PowerShell version](https://github.com/PowerShell/PowerShell) which has an new [ConvertTo-Csv](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertto-csv) with a [`-quotefields`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertto-csv#-quotefields) parameter. – iRon Oct 12 '22 at 08:59
  • this is not possible, in our company we have to use an older version for several production reasons – user18209625 Oct 12 '22 at 09:01

1 Answers1

2

As commented, it is recommended to install the latest PowerShell version which has a 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:

  1. The first ^ marks the beginning of a line
  2. ([^"]*) selects all successive characters that aren't double quotes
  3. '$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.
iRon
  • 20,463
  • 10
  • 53
  • 79