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.
Add a comment
|
1 Answer
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+)"
4 Comments
Modro
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 $_.Property3Scott Taylor
Works great except if the value is v0047003 it's changed to v-47-3. I need to keep all zeros on the second "-".
boxdog
Odd. Doesn't do that for me.
v0047003 becomes v-47003 as expected.Modro
@boxdog , same here, i get also
v-47003 as expected