Home > Enterprise >  Populating a Given Range
Populating a Given Range

Time:12-15

I have an output from text that needs to have the values in between filled. For example the text file will have:

C1-C5,C10-C12

I need that to then populate C1,C2,C3,C4,C5,C10,C11,C12.

So far what I know I can do is this:

((Get-Content -path C:\Users\person\Desktop\test\test.txt) -replace '-','..')| 
  Set-Content -Path C:\Users\person\Desktop\test\test.txt

Get-Content -path C:\Users\person\Desktop\test\test.txt

Is there a way to then use the ".." to fill inbetween?

I'm still relatively new to Powershell, so bare with me.

Thanks!

CodePudding user response:

You could use the [RegEx]::Replace() method to do this. You'd need to replace any case of X#-X# with the iterated version. You could do this inline simply enough, and split it on commas after if you wanted individual items. This does assume that all of your ranges have a A5-A12 format where it is a letter/number, followed by the same letter and another number, with a dash in-between them. If you had other cases where there is no letter you could address that similarly afterwards with a little modification to the same process that excludes the letter bit.

Here's how I'd do it; I'd setup a scriptblock that parses the letter off the start of a set, strips the letters from the set, and splits it on the dash, then iterates the numbers, adding the letter back on each iteration and joining them all back with a comma.

$RawText = 'C1-C5, R5-R10, P10-P20'

$SB={Param($Set)
    $Letter = $Set -replace '(?<=^\D )\d.*'
    $from,$to=$Set -replace '[a-zA-Z]' -split '-'
    ($from..$to|%{"$Letter$_"}) -join ', '
}

[regex]::Replace($RawText,'(\w \d -\w \d )',$SB)

That outputs:

C1, C2, C3, C4, C5, R5, R6, R7, R8, R9, R10, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20

You could split that ', ' to get each as it's own thing like:

[regex]::Replace($RawText,'(\w \d -\w \d )',$SB) -split ', '

This also works if you have input like:

A3, C1-C5, R5-R10, F7, G1, P10-P20, X9

Outputting:

A3, C1, C2, C3, C4, C5, R5, R6, R7, R8, R9, R10, F7, G1, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, X9
  • Related