【问题标题】:Windows Console: Extract specific range of lines from a huge file to a new fileWindows 控制台:从大文件中提取特定范围的行到新文件
【发布时间】:2021-09-02 19:30:28
【问题描述】:

我想从第 X 行到第 Y 行的巨大 CSV 文件(约 15GB,600 万行)中提取数千行,而不使用大量 RAM。

使用命令行解释器中的 Powershell 2.0,我能够提取前 2000 行:

PS> Get-Content -TotalCount 2000 file.csv > first_lines.csv,

和最后 2000 行(跳过前 5,998,000 行),来自 cmd.exe 解释器本身,带有:

more +5998000 file.csv > last_lines.csv,

但现在我想从第 3,000,001 行提取到第 3,002,000 行,而不必创建巨大的新文件或对 RAM 施加太大压力。

提前致谢!

【问题讨论】:

  • PowerShell 2.0 是十多年前发布的;在 2009 年。值得努力进入当前的 Windows Powershell 5.1,或者更好的是 PowerShell Core 7.1。 github.com/PowerShell/PowerShell

标签: cmd line extract powershell-2.0 windows-console


【解决方案1】:

Select-Object-Index参数可以指定范围。

Get-Content -Path .\file.csv | Select-Object -Index (3000001..3002000)

使用变量使其更加灵活。

$x = 3000001
$y = 3002000
Get-Content -Path .\file.csv | Select-Object -Index ($x..$y)

【讨论】:

    【解决方案2】:

    下面呢:

    rem // Initialise counter:
    set /A "COUNT=0"
    rem // Write to output file:
    > "first_lines.csv" (
        rem // Loop through lines beginning at a certain line number:
        for /F usebackq^ skip^=5998000^ delims^=^ eol^= %%I in ("file.csv") do (
        rem // This is an alternative way:
        rem for /F delims^=^ eol^= %%I in ('more +5998000 "file.csv"') do (
            rem // Return currently iterated line:
            echo(%%I
            rem // Increment counter:
            set /A "COUNT+=1"
            rem // Check counter state and conditionally terminate loop:
            setlocal EnableDelayedExpansion
            if !COUNT! geq 2000 goto :NEXT
            endlocal
        )
    )
    :NEXT
    

    注意for /F 会跳过空白行,并且这些行限制为大约 8190 个字符/字节。

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 2012-06-24
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多