How to find & replace a string appearing at nth position in a pipe delimited csv file using powershell

大兔子大兔子 提交于 2020-06-17 09:51:27

问题


I have csv files which contain data as per below sample

MACADD||TEST|Street1|CITY||Taiwan|||10000000|||FIRE||Taiwan||||||||12 days||30 Days|DDTE||812148709231890||124-Taiwan|DENE|||

I want to replace the 7th value in every csv files but problem is when I replace it the entire data gets separated by comma as the replacement value contained comma in it.

is there any way to ignore/escape commas while after the replacement has happened so that entire data appears in 1st cell of the final csv file.

$Files = Get-content -Path F:\Newfolder\*.csv

 $CountryCodeLookup = @{
    'USA'= 'United States'
    'Taiwan' = "Taiwan, Republic of China" # for this item csv file become strange
    'Delhi' = "Delhi, Capital of India, U.T" # for this item csv file become strange
    }

foreach ($File in $Files)
    {
    $DelimCount = ($File -replace '[^|]', '').Length
    $CSV_Thing = ConvertFrom-Csv -Delimiter '|' -InputObject $File -Header @(1..$DelimCount)

    If ($CountryCodeLookup.ContainsKey($CSV_Thing.7))    
    {
    $CSV_Thing.7 = $CountryCodeLookup[$CSV_Thing.7]
    }


    $OutString = (($CSV_Thing |
        ConvertTo-Csv -Delimiter '|' -NoTypeInformation |
        Select-Object -Skip 1) -replace '"', '') + '|' | Set-Content $File.PSPath -Force

    }



回答1:


$Files = Get-content -Path F:\Newfolder\*.txt
$Path = "F:\Newfolder"

 $CountryCodeLookup = @{
    'USA'= 'United States'
    'Taiwan' = "Taiwan, Republic of China" # for this item csv file become strange
    'Delhi' = "Delhi, Capital of India, U.T" # for this item csv file become strange
    }

foreach ($File in $Files)
    {
    $DelimCount = ($File -replace '[^|]', '').Length
    $CSV_Thing = ConvertFrom-Csv -Delimiter '|' -InputObject $File -Header @(1..$DelimCount)

    If ($CountryCodeLookup.ContainsKey($CSV_Thing.7))    
    {
    $CSV_Thing.7 = $CountryCodeLookup[$CSV_Thing.7]
    }


    $OutString = (($CSV_Thing |
        ConvertTo-Csv -Delimiter '|' -NoTypeInformation |
        Select-Object -Skip 1) -replace '"', '') + '|' | Set-Content $File.PSPath -Force

    }


    $files = Get-ChildItem $Path | where { ! $_.PSIsContainer }
foreach ($file in $files){
    $newFileName = ($file.Fullname) -Replace ".txt",".csv"
    Get-Content $file.FullName | Out-File $newFileName
}


来源:https://stackoverflow.com/questions/62045851/how-to-find-replace-a-string-appearing-at-nth-position-in-a-pipe-delimited-csv

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