8

I am trying to run the following command on a very large text file. However, it's very slow

((cat largefile.txt | select -first 1).split(",")).count()

Is an alternative fast way in powershell? It seems the command will scan the whole file no matter what.

2 Answers 2

12

To only get the first x number of lines in a text file, use the –totalcount parameter:

((Get-Content largefile.txt -totalcount 1).split(",")).count
1
  • 2
    This method loads the entire file into memory first, before taking the first line.
    – Ten98
    Commented Jun 24, 2014 at 9:56
10

It's worse than that - it will load the whole file and turn it into a string array.

Use the native .NET libraries to load just the first line:

$reader = [System.IO.File]::OpenText("largefile.txt")
$line = $reader.ReadLine()
$reader.Close()

(borrowed from How to process a file in Powershell line-by-line as a stream)

3
  • What about the last lines or do you just have to wait for it to go all the way through?
    – Paul C
    Commented Jun 11, 2014 at 7:38
  • This method only loads the first line into memory, making it many times quicker than Get-Content on larger files.
    – Ten98
    Commented Jun 24, 2014 at 9:56
  • PowerShell 5.1 : Line 2 loads the whole file in memory Commented May 5, 2022 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.