Haythem Houissa
Haythem Houissa

Reputation: 41

substitute a variable in a string with another variable

I have a generated string like this:

$x = jhgkjh**May**-**JUN**ojklkjh-jkl

I want to substitute every occurrence in $x of a month abbreviation with the number of the month. So the result will look like this:

$x = jhgkjh**05**-**06**ojklkjh-jkl

For that I created 2 arrays:

$months = "Jan", "Feb", etc...
$Nmonths = "01", "02" , etc...

This loop doesn't work:

$i = 0
do {
$x = $x.replace('$months[$i]','$Nmonths[$i]')
$i = $i+1
}
until ("$i" -eq "12")
$x

Please help !

Upvotes: 0

Views: 60

Answers (2)

mjolinor
mjolinor

Reputation: 68273

The sample data looks a little odd with respect to the case of the month strings. Can't really tell if it's case sensitive or not, so here's two slightly different solutions. Starting whe a hash table of month abbreviations and numbers:

$Months=@{
Jan = '01'
Feb = '02'
Mar = '03'
Apr = '04'
May = '05'
Jun = '06'
Jul = '07'
Aug = '08'
Sep = '09'
Oct = '10'
Nov = '11'
Dec = '12'
}

Using string.replace()

$string = '$x = jhgkjh**May**-**Jun**ojklkjh-jkl'
foreach ($Month in $Months.Keys)
 { $string = $string.Replace($Month,$Months.$Month)}

Using the -Replace operator

 $string = '$x = jhgkjh**May**-**JUN**ojklkjh-jkl'
 foreach ($Month in $Months.Keys)
 { $string = $string -Replace $Month,$Months.$Month }  

The string.replace() method is faster, but the -Replace operator will be more flexible with regard to case sensitivity.

Either way, the foreach loop should be faster than foreach-object

Upvotes: 1

Joseph Alcorn
Joseph Alcorn

Reputation: 2442

Powershell does not have a do until construct. Try this one liner instead of your loop.

0..11 | % { $x = $x -replace $months[$_],$Nmonths[$_] }

The .. Operator creates a range of integers between the first number and the last.

If you still want to use a traditional flow control structure you can replace the until line with this

while($i -lt 12)

Upvotes: 0

Related Questions