20

Can i skip multiple lines with the -skip option?

gc d:\testfile.txt | select -skip 3

works but what to do if i want to delet line 3-7 ??

icnivad
  • 2,231
  • 8
  • 29
  • 35

5 Answers5

23

You can also use the readcount property to exclude lines:

get-content d:\testfile.txt | where {$_.readcount -lt 3 -or $_.readcount -gt 7}
Chad Miller
  • 40,127
  • 3
  • 30
  • 34
8

If I need to select only some lines, I would directly index into the array:

$x = gc c:\test.txt
$x[(0..2) + (8..($x.Length-1))]

It is also possible to create a function Skip-Objects

function Skip-Object {
    param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][PsObject]$InputObject,
        [Parameter(Mandatory=$true)][int]$From,
        [Parameter(Mandatory=$true)][int]$To
    )

    begin {
        $i = -1
    }
    process {
        $i++
        if ($i -lt $from -or $i -gt $to)  {
            $InputObject
        }
    }
}

1..6 | skip-object -from 1 -to 2   #returns 1,4,5,6
'a','b','c','d','e' | skip-object -from 1 -to 2 #returns a, d, e
stej
  • 28,745
  • 11
  • 71
  • 104
5

The PowerShell Community Extensions comes with a Skip-Object cmdlet:

PS> 0..10 | Skip-Object -Index (3..7)
0
1
2
8
9
10

Note that the Index parameter is 0-based.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
3

Similarly, without extensions (note that -skip needs the number of items to skip, and not an index)

$content = get-content d:\testfile.txt
($content | select -first 3), ($content | select -skip 8)
Frank Bryce
  • 8,076
  • 4
  • 38
  • 56
1
$list = @(1..9)
@(($list | Select-Object -First 2), ($list | Select-Object -Skip 7))

$list = @(1..19)
@(($list | Select-Object -First 2), ($list | Select-Object -Skip 7 -First 2))

-First = Take()

ZSkycat
  • 9,372
  • 2
  • 8
  • 5