0

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.

1 Answer 1

2

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+)"
Sign up to request clarification or add additional context in comments.

4 Comments

And If you dont have headers you can do it like this Import-Csv .\data.csv -Header A,B,C and then use $_.C instead of $_.Property3
Works great except if the value is v0047003 it's changed to v-47-3. I need to keep all zeros on the second "-".
Odd. Doesn't do that for me. v0047003 becomes v-47003 as expected.
@boxdog , same here, i get also v-47003 as expected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.