Powershell select-object跳过多行?

icn*_*vad 17 powershell

我可以使用-skip选项跳过多行吗?

gc d:\testfile.txt | select -skip 3
Run Code Online (Sandbox Code Playgroud)

工作,但如果我想要删除3-7行?该怎么办?

Cha*_*ler 21

您还可以使用readcount属性排除行:

get-content d:\testfile.txt | where {$_.readcount -lt 3 -or $_.readcount -gt 7}
Run Code Online (Sandbox Code Playgroud)


ste*_*tej 8

如果我只需要选择一些行,我会直接索引到数组:

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

也可以创建一个函数 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
Run Code Online (Sandbox Code Playgroud)


Kei*_*ill 5

PowerShell社区扩展附带 Skip-Object cmdlet:

PS> 0..10 | Skip-Object -Index (3..7)
0
1
2
8
9
10
Run Code Online (Sandbox Code Playgroud)

请注意,Index 参数是从 0 开始的。