Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace first character in string

Tags:

powershell

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:

$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?

like image 801
Fredrik Fredén Avatar asked Jan 05 '23 20:01

Fredrik Fredén


1 Answers

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,

$_.mobile = $_.mobile -replace "^0", "+46"
like image 176
vonPryz Avatar answered Jan 14 '23 05:01

vonPryz