Replace letter " to "" in export-csv powershell

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of radhaswarup sar radhaswarup sar 2 weeks, 2 days ago.

  • Author
    Posts
  • #74612
    Profile photo of radhaswarup sar
    radhaswarup sar
    Participant

    Hi All,
    I am trying to work on a requirement. When there is a " will come in a field in csv it should convert to "".

    Could you please help making that powershell command. I have written below so far.

    Input Output
    "sample" ""sample""
    "Samp"le ""samp"le"

    Import-Csv "C:\Users\RSar-2\Desktop\Accutrac.csv" -Delimiter '~' | where {$_.USER_NAME -ne "———"} | ForEach-Object {
    if ($_.Project_Desc -eq 'VERTIGO') {
    $_.Project_Desc = '"VERTIGO"'
    }
    $_ | Export-Csv -Path "C:\Users\RSar-2\Desktop\$($_.USER_NAME).csv" -NoTypeInformation -Append -Delimiter '~'
    }

  • #74617

    Hi

    How about if you export '"' + $_ + '"'? Dirty but works.

    '"yeah"','"wohoo"' | ForEach-object {
    
        '"' + $_ + '"'
    
    }
    ""yeah""
    ""wohoo""
    

    Tried also following:

    '"yeah"','"wohoo"' | ForEach-object {
    
        $($_).insert(0,'"').insert(($_.length)+1,'"')
    
    }
    ""yeah""
    ""wohoo""
    

    Regards

    Jarkko

  • #74642
    Profile photo of random commandline
    random commandline
    Participant

    Use the -replace operator.

    Import-Csv "C:\Users\RSar-2\Desktop\Accutrac.csv" -Delimiter '~' | 
    where {$_.USER_NAME -ne "———"} | ForEach-Object {$_ -replace '"','""'} |
    Export-Csv -Path "C:\Users\RSar-2\Desktop\$($_.USER_NAME).csv" -NoTypeInformation -Append -Delimiter '~'
    
    • #74645

      Hi

      Isn't that also replace the quotamarks inside the string that do not need to be doubled?

      Input Output
      "sample" ""sample""
      "Samp"le ""samp"le"

      Regards

      Jarkko

    • #74696
      Profile photo of radhaswarup sar
      radhaswarup sar
      Participant

      Now I am replacing " to some other characters and then converting them back to " after new csv is prepared. That helped my cause.

      Get-ChildItem 'E:\test\*.csv' -Recurse | ForEach {
      (Get-Content $_ | ForEach { $_ -replace '"', '#' }) |
      Set-Content $_
      }

      Get-ChildItem 'E:\test\*.csv' -Recurse | ForEach {
      (Get-Content $_ | ForEach { $_ -replace '#', '"' }) |
      Set-Content $_
      }

      Thanks for your inputs Jarkko!! Apreciated!

You must be logged in to reply to this topic.