Please check the below script in PowerShell. I have made an assumption that there will be only one country. The entries can be jumbled in any way.
Also, I assume that there is this below row as the first row in your CSV for the headers:
Country,State,City
You can use similar logic in any other Programming language as well.
$csvInput = Import-Csv -Path "C:\Data\Test\abc.csv" | Sort-Object State
$outputFileContent = @()
$outputFileContent += ($csvInput[0].Country)
$oldState = ""
$newState = ""
foreach($csvRow in $csvInput)
{
$newState = $csvRow.State
if($newState -ne $oldState)
{
$outputFileContent+= ( "-" + $csvRow.State)
}
$oldState = $newState
$outputFileContent += ("--" + $csvRow.City)
}
$outputFileContent | Out-File -FilePath "C:\Data\Test\testOutput.txt"
Replace “C:\Data\Test\abc.csv” with your input CSV file and “C:\Data\Test\testOutput.txt” with the path to your output file.
1
solved How do I convert this CSV to a better format using PHP?