Scott Taylor
Scott Taylor

Reputation: 63

Powershell replace text in a field from import-csv

I'm reading in a large csv file via Import-CSV and have a column of data with the following format; v00001048, v00019045, or v0036905. I'd like to replace all the zero's (0) after the v but before any number not a zero so the above text becomes; v-1048, v-19045, or v-36905. Done plenty of searches without successful results.

Upvotes: 0

Views: 1981

Answers (1)

boxdog
boxdog

Reputation: 8432

If you have a CSV (say, 'data.csv') with data like this:

Property1,Property2,Property3
SomeText,MoreText,v00001048

Then you can replace the leading zeros in Property3 using this technique:

$data = Import-csv .\data.csv 

$data | 
    ForEach-Object {
        $_.Property3 = $_.Property3 -replace "(?<=v)0+(?=\d+)","-"
    }

If the property doesn't have any leading zeros to start with (e.g. v1048) this will leave it untouched. If you'd like it to insert the '-' anyway, then change the regex pattern to:

"(?<=v)0*(?=\d+)"

Upvotes: 2

Related Questions