问题
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