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
  • 24,345
  • 44
  • 175
  • 352

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
  • 14,930
  • 1
  • 31
  • 35
9

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,335
  • 2
  • 36
  • 55