Wednesday, September 9, 2009

Return the last n' lines from a text file.

I am a PoSh fan (PowerShell for those who are unfamiliar) and hence, have decided to challenge myself, to stretch my knowledge & ability, by posting daily one liners.  Here is my first:

In my world logging is king for any activity we do, but I hate opening file after file to read the last few lines.  Instead, I'd rather have PoSh do it for me:

EXPANDED

$list = Get-Content yourfile.txt
$Count = $list.Count
foreach ($line in $list) {
  $ReadCount = $line.ReadCount
  if ($ReadCount -gt ($Count -3) {
    $line
  }
}
CODE: [Copy:Expand]
PEICE BY PEICE
$list = Get-Content yourfile.txt
We need to open our text file and put each line into an object to parse through.

$Count = $list.Count
Count each line to find our total.

foreach ($line in $list)
Parse through each line.

$ReadCount = $line.ReadCount
Find the line number we are currently on.

if ($ReadCount -gt ($Count -3)
This line looks for the last 3 lines based on the line number and the total number of lines minus 3. Replace "3" with with the number of lines you'd like to grab.

$line
Writes the line to the console

ONELINER
foreach ($line in ($list = gc yourfile.txt)) { if ($line.ReadCount -gt ($list.Count - 3)) { $line } }
TaDa!! A oneliner to grab the last n' number of lines from a given text file.

Notice that $list = gc yourfile.txt is still in place. In order to count the lines we have to use the method .Count. Without defining $list there is no quick way to gather the total number of lines in the file.

ALIASES
gc = Get-Content

0 comments: