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.

ca9163d9
  • 27,283
  • 64
  • 210
  • 413

2 Answers2

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
jon Z
  • 15,838
  • 1
  • 33
  • 35
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)

Community
  • 1
  • 1
Arithmomaniac
  • 4,604
  • 3
  • 38
  • 58