System.IO.StreamReader.ReadLine() in reverse mode

Welcome Forums General PowerShell Q&A System.IO.StreamReader.ReadLine() in reverse mode

This topic contains 5 replies, has 4 voices, and was last updated by

 
Participant
3 years, 2 months ago.

  • Author
    Posts
  • #29053

    Participant
    Points: 0
    Rank: Member

    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

  • #29054

    Participant
    Points: 166
    Helping Hand
    Rank: Participant

    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
    
    
  • #29055

    Keymaster
    Points: 1,639
    Helping HandTeam Member
    Rank: Community Hero

    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.

  • #29063

    Participant
    Points: 0
    Rank: Member

    Thank you

  • #29065

    Member
    Points: 0
    Rank: Member

    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.

  • #29066

    Participant
    Points: 166
    Helping Hand
    Rank: Participant

    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
    

The topic ‘System.IO.StreamReader.ReadLine() in reverse mode’ is closed to new replies.