PowerShell equivalent for "head -n-3"?

likso picture likso · Apr 9, 2012 · Viewed 18.8k times · Source

I've been able to track down basic head/tail functionality:

head -10 myfile <==> cat myfile | select -first 10
tail -10 myfile <==> cat myfile | select -last 10

But if I want to list all lines except the last three or all lines except the first three, how do you do that? In Unix, I could do "head -n-3" or "tail -n+4". It is not obvious how this should be done for PowerShell.

Answer

Michael Sorens picture Michael Sorens · Apr 11, 2012

Useful information is spread across other answers here, but I think it is useful to have a concise summary:

All lines except the first three

1..10 | Select-Object -skip 3
returns (one per line): 4 5 6 7 8 9 10

All lines except the last three

1..10 | Select-Object -skip 3 -last 10
returns (one per line): 1 2 3 4 5 6 7

That is, you can do it with built-in PowerShell commands, but there's that annoyance of having to specify the size going in. A simple workaround is to just use a constant larger than any possible input and you will not need to know the size a priori:

1..10 | Select-Object -skip 3 -last 10000000
returns (one per line): 1 2 3 4 5 6 7

A cleaner syntax is to use, as Keith Hill suggested, the Skip-Object cmdlet from PowerShell Community Extensions (the Skip-Last function in Goyuix's answer performs equivalently but using PSCX saves you from having to maintain the code):

1..10 | Skip-Object -last 3
returns (one per line): 1 2 3 4 5 6 7

First three lines

1..10 | Select-Object –first 3
returns (one per line): 1 2 3

Last three lines

1..10 | Select-Object –last 3
returns (one per line): 8 9 10

Middle four lines

(This works because the -skip is processed before the -first, regardless of the order of parameters in the invocation.)

1..10 | Select-Object -skip 3 -first 4
returns (one per line): 4 5 6 7