Search code examples
powershelltextlarge-files

Powershell - How do I extract the first line of all text files in a directory into a single output file?


I have a directory with about 10'000 text files of varying lengths. All over 1GB in size.

I need to extract the first line of each file and insert it into a new text file in the same directory.

I've tried the usual MS-DOS batch file method, and it crashes due to the files being too large.

Is there a way of doing this in Powershell using Streamreader?


Solution

  • In order to read only one line, you can also use :

    $file = new-object System.IO.StreamReader($filename)
    $file.ReadLine()
    $file.close()
    

    Using OutVariable you can write it in one line :

    $text = (new-object System.IO.StreamReader($filename) -OutVariable $file).ReadLine();$file.Close()