Powershell-如何将目录中所有文本文件的第一行提取到单个输出文件中?

Ten*_*n98 4 powershell text large-files

我的目录中包含大约10'000个不同长度的文本文件。全部超过1GB。

我需要提取每个文件的第一行,并将其插入到同一目录中的新文本文件中。

我尝试了通常的MS-DOS批处理文件方法,由于文件太大,它崩溃了。

有没有办法在Powershell中使用Streamreader做到这一点?

Ric*_*ard 6

编辑:当然在那里以一种内置的方式:

$firstLine = Get-Content -Path $fileName -TotalCount 1
Run Code Online (Sandbox Code Playgroud)

[Ack Raf的评论]


原版的:

我建议您看一下File.ReadLines:此方法延迟读取文件的内容–仅在返回的枚举数的每次迭代中读取内容。

我不确定是否Select-Object -first 1会在一行之后主动停止管道,如果这样做,那是获得第一行的最简单方法:

$firstLine = [IO.File]::ReadLines($filename, [text.encoding]::UTF8) | Select-Object -first 1
Run Code Online (Sandbox Code Playgroud)

否则类似:

$lines = [IO.File]::ReadLines($filename, [text.encoding]::UTF8); # adjust to correct encoding
$lineEnum = $lines.GetEncumerator();
if ($lineEnum.MoveNext()) {
  $firstLine = $lineEnum.Current;
} else {
  # No lines in file
}
Run Code Online (Sandbox Code Playgroud)

注意 这假定至少PowerShell V3使用.NET V4。


JPB*_*anc 5

为了只读一行,您还可以使用:

$file = new-object System.IO.StreamReader($filename)
$file.ReadLine()
$file.close()
Run Code Online (Sandbox Code Playgroud)

使用OutVariable可以将其写成一行:

$text = (new-object System.IO.StreamReader($filename) -OutVariable $file).ReadLine();$file.Close()
Run Code Online (Sandbox Code Playgroud)