Author Posts

August 27, 2015 at 7:37 am

Hi, is it possible to read lines from text file from the end to the beginning?
Or is it possible WriteLine to specific row number?
I need read big files, so I need use StreamReader in reverse or StreamWriter to write line into specific row number (write after header).
Thanks
Peter

August 27, 2015 at 7:51 am

If you use Get-Content to read a file, it imports each line into an array. You can then just loop through the file backwards and break the loop when you find the content your looking for:

PS C:\> $content = Get-Content C:\Temp\test1.txt

PS C:\> $content.Count
4

PS C:\> $content
This
is
a
test

PS C:\> for($i = $content.Count -1;$i -ge 0;$i--){$content[$i]}
test
a
is
This

August 27, 2015 at 7:57 am

StreamReader/Writer are only able to move through the file from beginning to end; they don't offer random or reverse access. The most you could do is read and immediately write existing data from the front of the file, and then write your new data. It has more to do with how the data is stored on disk than anything else. There's no real way to "find" the end of the file without reading through the entire thing.

The potential difficulty with using Get-Content, as suggested, is that for a very large file it'll consume a ton of memory. It's really the only option, though, unless you can move the data into a different, more structured format – like a SQL Server database or something.

August 27, 2015 at 9:28 am

You can probably take inspiration from C# code and examples to accomplish this same task. For instance: http://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c-sharp

It should be fairly straightforward to rewrite that sort of thing in PowerShell.

August 27, 2015 at 10:30 am

If you know that the content you are looking for is in the last 10 lines of 100 lines, you can use the -Tail option of Get-Content which should save you maintaining 90 lines of text that you aren't going to need\read:

PS C:\> $content = Get-Content C:\Temp\test1.txt -Tail 2

PS C:\> $content
a
test