Windows – How to display the first N lines of a command output in Windows? (the equivalent of Unix command “head”)

command-line-interfacewindowswindows-command-prompt

I need an equivalent of the Unix head command (display the first N lines of the output). This is what I'm using currently:

tasklist | find /N " " | findstr /r \[[0-9]\]

The above code displays the first 10 lines of tasklist's output. find /N " " prepends a line number to the start of each line while findstr /r \[[0-9]\] extracts the first 10 lines using regex.

Above code works, but I need to specify any range. Due to the fact that regular expressions are not implemented according to the standards in Windows, I can't get anything else to work.

How can I extract arbitrary lines from a cmd output? It is important to do this with a one-liner. No scripts!

Best Answer

Powershell.

PS C:\> netstat | Select -First 20

Edit: I have a feeling that you're going to insist that you're only able to use cmd.exe circa 1989, but that's not true. Powershell is baked into every OS version Vista+, and is installable on XP/2003. It is the future of Windows.

Edit: Alright, have it your way.

C:\> netstat -an > temp.txt && for /l %l in (1,1,10) do @for /f "tokens=1,2* delims=:" %a in ('findstr /n /r "^" temp.txt ^| findstr /r "^%l:"') do @echo %b

Will display the first 10 lines of the output of netstat.