On windows, using Powershell, what are the equivalent commands to linux's head
, tail
, more
, less
and sed
?
This question is related to
windows
powershell
$Push_Pop = $ErrorActionPreference #Suppresses errors
$ErrorActionPreference = “SilentlyContinue” #Suppresses errors
#Script
#gc .\output\*.csv -ReadCount 5 | %{$_;throw "pipeline end!"} # head
#gc .\output\*.csv | %{$num=0;}{$num++;"$num $_"} # cat -n
gc .\output\*.csv | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed
#End Script
$ErrorActionPreference = $Push_Pop #Suppresses errors
You don't get all the errors with the pushpop code BTW, your code only works with the "sed" option. All the rest ignores anything but gc and path.
If you need to query large (or small) log files on Windows, the best tool I have found is Microsoft's free Log Parser 2.2. You can call it from PowerShell if you want and it will do all the heavy lifting for you, and very fast too.
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
I got some better solutions:
gc log.txt -ReadCount 5 | %{$_;throw "pipeline end!"} # head
gc log.txt | %{$num=0;}{$num++;"$num $_"} # cat -n
gc log.txt | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed
"-TotalCount" in this instance responds exactly like "-head". You have to use -TotalCount or -head to run the command like that. But -TotalCount is misleading - it does not work in ACTUALLY giving you ANY counts...
gc -TotalCount 25 C:\scripts\logs\robocopy_report.txt
The above script, tested in PS 5.1 is the SAME response as below...
gc -head 25 C:\scripts\logs\robocopy_report.txt
So then just use '-head 25" already!
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.
Source: Stackoverflow.com