PoshCode Archive  Artifact [5ec5d78f45]

Artifact 5ec5d78f4538061e1785b47f6ca1faa50ca39b8795ef5ec7d6c191ee46865e62:

  • File Tac-reverse-cat.ps1 — part of check-in [fff5e1e04d] at 2018-06-10 13:39:30 on branch trunk — Originally posted by Keith Hill on microsoft.public.windows.powershell. (user: halr9000 size: 1008)

# encoding: ascii
# api: powershell
# title: Tac (reverse cat)
# description: Originally posted by Keith Hill on microsoft.public.windows.powershell.
# version: 0.1
# author: halr9000
# license: CC0
# x-poshcode-id: 433
# x-archived: 2017-05-22T03:52:08
# x-published: 2009-06-26T07:20:00
#
# This script reads the content of a file backwards, from the end to the beginning.
# NOTE: a space is inserted between every char if the file is Unicode
#
# From "Unix like command for tac?" thread on posh NG
# solution by Keith Hill

param([string]$path)

$fs = New-Object System.IO.FileStream ((Resolve-Path $path), 'Open', 'Read')
trap { $fs.Close(); break }

$pos = $fs.Length
$sb = New-Object System.Text.StringBuilder
while (--$pos -ge 0) {
    [void]$fs.Seek($pos, 'Begin')
    $ch = [char]$fs.ReadByte()
    if ($ch -eq "`n" -and $sb.Length -gt 0) {
        $sb.ToString().TrimEnd()
        $sb.Length = 0
    }
    [void]$sb.Insert(0, [char]$ch)
}
$sb.ToString().TrimEnd()