matandked
matandked

Reputation: 1573

remove each third element in PowerShell array

I have very long string which I copy and paste from external program to PowerShell. After splitting it (

$variable=$variable.split("`n")

) I received array from which i Want remove every third element. What is most convenient way of accomplishing it? I thought about loop from

0 to $variable.lenght()-1

and check if i can be divided by three, but maybe there is other way?

Upvotes: 0

Views: 5943

Answers (5)

mjolinor
mjolinor

Reputation: 68341

$new_variable = $variable | foreach {$i=1} {if ($i++ %3){$_}}

Upvotes: 1

zx38
zx38

Reputation: 114

$i = 0
$variable = $variable.split("`n") | ? {++$i % 3}

Upvotes: 1

Shay Levy
Shay Levy

Reputation: 126932

Or

0..($variable.count-1) | foreach { if($_%3) {$variable[$_]} }

Upvotes: 0

Jeffery Hicks
Jeffery Hicks

Reputation: 943

$new=for ($i=2;$i -lt $array.count;$i+=3) {$array[$i]}

This will start at the 3rd element and get every third. Pipelined output is saved to $new.

Upvotes: 2

CB.
CB.

Reputation: 60976

If you need to remove values any 3 positions (0-based: 2,5,8,11,14 and so on) in the array use something like this:

$newArray = @()
0..($variable.length) | % {
    if ((($_+1) % 3 ) -ne 0) {
        $newArray += $variable[$_]
    }
}

Upvotes: 2

Related Questions