How to do what head, tail, more, less, sed do in Powershell?
Here are the built-in ways to do head
and tail
. Don't use pipes because if you have a large file, it will be extremely slow. Using these built-in options will be extremely fast even for huge files.
gc log.txt -head 10
gc log.txt -tail 10
gc log.txt -tail 10 -wait # equivalent to tail -f
Get-Content
(alias: gc
) is your usual option for reading a text file. You can then filter further:
gc log.txt | select -first 10 # head
gc -TotalCount 10 log.txt # also head
gc log.txt | select -last 10 # tail
gc -Tail 10 log.txt # also tail (since PSv3), also much faster than above option
gc log.txt | more # or less if you have it installed
gc log.txt | %{ $_ -replace '\d+', '($0)' } # sed
This works well enough for small files, larger ones (more than a few MiB) are probably a bit slow.
The PowerShell Community Extensions include some cmdlets for specialised file stuff (e.g. Get-FileTail).
more.exe
exists on Windows, ports of less
are easily found (and the PowerShell Community Extensions, PSCX, includes one).
PowerShell doesn't really provide any alternative to separate programs for either, but for structured data Out-Grid
can be helpful.
Head
and Tail
can both be emulated with Select-Object
using the -First
and -Last
parameters respectively.
Sed
functions are all available but structured rather differently. The filtering options are available in Where-Object
(or via Foreach-Object
and some state for ranges). Other, transforming, operations can be done with Select-Object
and Foreach-Object
.
However as PowerShell passes (.NET) objects – with all their typed structure, eg. dates remain DateTime
instances – rather than just strings, which each command needs to parse itself, much of sed
and other such programs are redundant.