Created
June 12, 2017 18:44
-
-
Save milesgratz/f81322ecdc4c783c6f06308ce90ff963 to your computer and use it in GitHub Desktop.
Replace an individual rows in a CSV by indexing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
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