Powershell select-object跳过多行?

时间:2022-10-17 04:24:32

Can i skip multiple lines with the -skip option?

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

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

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

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

4 个解决方案

#1


20  

You can also use the readcount property to exclude lines:

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

get-content d:\testfile.txt | where {$_.readcount -lt 3 -or $_.readcount -gt 7}

#2


7  

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

也可以创建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

#3


4  

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

PowerShell社区扩展随附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.

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

#4


2  

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

同样,没有扩展(请注意-skip需要跳过的项目数,而不是索引)

$content = get-content d:\testfile.txt
($content | select -first 3), ($content | select -skip 8)

#1


20  

You can also use the readcount property to exclude lines:

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

get-content d:\testfile.txt | where {$_.readcount -lt 3 -or $_.readcount -gt 7}

#2


7  

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

也可以创建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

#3


4  

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

PowerShell社区扩展随附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.

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

#4


2  

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

同样,没有扩展(请注意-skip需要跳过的项目数,而不是索引)

$content = get-content d:\testfile.txt
($content | select -first 3), ($content | select -skip 8)