Adeel ASIF
Adeel ASIF

Reputation: 3534

How to insert 0 in a string

this is my array :

eth1
eth12
eth5
eth11

When my string contains a number between 1 and 9 i want to add a 0 before, to obtain an array like this :

eth01
eth12
eth05
eth11

How can i achieve this? i don't know how to modify a string like this :/

Thanks

Upvotes: 0

Views: 129

Answers (3)

Shay Levy
Shay Levy

Reputation: 126762

Another option:

$if -replace '(?<=\D)(\d)$', '0$1'

Upvotes: 4

Lo&#239;c MICHEL
Lo&#239;c MICHEL

Reputation: 26150

a more tortuous way than Ansgar's :)

$a=@("eth1","eth12","eth5")

$a|%{
    $slice=$_.split("h");
    if([int]$slice[1] -le 9){
        $slice[1]="0"+$slice[1]
    }
join-string -strings $slice -separator("h")
}

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Like this:

$if = 'eth1', 'eth12', 'eth5', 'eth11'
$if -replace '(\D+)(\d)$', '${1}0$2'

Upvotes: 9

Related Questions