mhn
mhn

Reputation: 2750

Exclude index in powershell

I have a very simple requirement of removing couple of lines in a file. I found little help on the net , where we can make use of Index. Suppose i want to select 5th line i use

Get-Content file.txt | Select -Index 4

Similarly, what if i dont need the 5th and 6th line? How would the statement change?

Get-Content file.txt | Select -Index -ne 4

I tried using -ne between -Index and the number. It did not work. neither did "!=".

Also the below code gives no error but not the desired output

$tmp = $test  |   where {$_.Index -ne 4,5 }

Upvotes: 0

Views: 477

Answers (4)

Kirill Pashkov
Kirill Pashkov

Reputation: 3236

Convert this as an array and use RemoveRange method(ind index, int count)

[System.Collections.ArrayList]$text  = gc C:\file.txt
$text.RemoveRange(4,1)
$text

Upvotes: 0

Mike Shepard
Mike Shepard

Reputation: 18176

Try this:

get-content file.txt | select -index (0..3 + 5..10000)

It's a bit of a hack, but it works. Downside is that building the range takes some time. Also, adjust the 10000 to make sure you get the whole file.

Upvotes: 0

sodawillow
sodawillow

Reputation: 13176

Don't know about the Index property or parameter, but you can also achieve it like this :

$count = 0
$exclude = 4, 5
Get-Content "G:\input\sqlite.txt" | % {
    if($exclude -notcontains $count){ $_ }
    $count++
}

EDIT :

The ReadCount property holds the information you need :)

$exclude = 0, 1
Get-Content "G:\input\sqlite.txt" | Where-Object { $_.ReadCount -NotIn $exclude }

WARNING : as pointed by @PetSerAl and @Matt, ReadCount starts at 1 and not 0 like arrays

Upvotes: 1

user4003407
user4003407

Reputation: 22132

Pipeline elements does not have Index auto-property, but you can add it, if you wish:

function Add-Index {
    begin {
        $i=-1
    }
    process {
        Add-Member Index (++$i) -InputObject $_ -PassThru
    }
}

Then you can apply filtering by Index:

Get-Content file.txt | Add-Index | Where-Object Index -notin 4,5

Upvotes: 1

Related Questions