Question:
I have a CSV file where I want to replace the first character that is 0 with +46 but I can’t make this work as I want to.
I have the following code that works, but it works on all zeroes and not only the first one:
1 2 3 4 5 6 |
$csv = Import-Csv test.csv $csv | ForEach-Object { $_.mobile = $_.mobile.Replace("0", "+46") } $csv | Export-Csv -Encoding "UTF8" new-test.csv -NoTypeInformation |
Any idea how to make this work only on the first character in the string?
Answer:
This happens as String.Replace()
will replace all the occurrences.
In order to only replace the first one, use regular expressions. By using the beginning of line anchor, ^
, the replacement is limited to start of string. Like so,
1 2 |
$_.mobile = $_.mobile -replace "^0", "+46" |