繁体   English   中英

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

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

我有一个目录,大约有10,000个不同长度的文本文件。 全部超过1GB。

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

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

有没有办法使用Streamreader在Powershell中执行此操作?

编辑 :当然有内置的方式:

$firstLine = Get-Content -Path $fileName -TotalCount 1

[Ack Raf的评论]


原版的:

我建议查看File.ReadLines :这个方法懒惰地读取文件的内容 - 只读取返回的枚举器上每次迭代的内容。

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

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

否则之类的:

$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
}

NB。 这假设至少PowerShell V3使用.NET V4。

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

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

使用OutVariable,您可以将其写在一行:

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

短而甜蜜:

cd c:\path\to\my\text\files\
Get-Content *.txt -First 1 > output.txt

编辑2018年11月:根据文档,“ TotalCount参数将检索限制为前n行。 ”这似乎可以最大限度地减少资源使用。 自己测试并添加您的评论。

cd c:\path\to\my\text\files\
Get-Content *.txt -TotalCount 1 > output.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM