Skip to content

Instantly share code, notes, and snippets.

@milesgratz
Created June 12, 2017 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milesgratz/f81322ecdc4c783c6f06308ce90ff963 to your computer and use it in GitHub Desktop.
Save milesgratz/f81322ecdc4c783c6f06308ce90ff963 to your computer and use it in GitHub Desktop.
Replace an individual rows in a CSV by indexing
<#
Replace individual rows in a CSV
(if there are no multiline rows)
Define example input file
City Zipcode
---- -------
Phoenix, AZ 85001
Little Rock, AR 72201
Sacramento, CA Unknown
#>
$file = "C:\temp\example.csv"
$txt = Get-Content $file
$array = Import-Csv $file
# Check if indexing will be broken by file vs array length
If ($txt.Count -ne ($array.Count+1)){
Write-Host "Indexing will not work."
}
# Let's update Sacramento zip code in the file
$index = 0
$array | ForEach-Object {
# Check if Sacramento
If ($_.City -eq "Sacramento, CA")
{
# Define new zip code
$_.Zipcode = "94203"
# Replace individual row in file
$txt[$index+1] = $_ | ConvertTo-Csv -NoTypeInformation | Select -Skip 1
$txt | Set-Content $file
}
# Increment
$index++
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment