Before I tell you about recursion, I need to tell you about recursion.

I was working with a csv file last week where there were multiple empty fields on each row, not all of which were aligned.  I considered the problem briefly then fired up a powershell console with the intent of doing some import-csv for each loop to parse out the data. The [string]::replace() method would work fine for the first instance of two consecutive commas but I wanted to replace all instances of repeating commas.

I stopped to think about the best way to do this when I thought perhaps a little recursion would do the trick! I came up with this function:

function spit ($line){if ($line -match “,,”){spit $line.replace(“,,”,”,”)}else $line}

If the argument matches the pattern i.e. two consecutive commas I pass the argument with one comma removed back into the function, and keep doing this till the argument doesn’t match the pattern.  The function name was the first name that came into my mind because I wanted to spit out the results, which I was able to do nicely with

get-content filename.csv | % {spit $_}

As the joke goes…before you understand recursion you must first understand recursion.

If you’d like to learn recursion for yourself I found the following learning plan quite good

Learn Recursion

 

 

Share This

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.