Windows 控制台:将特定范围的行从一个大文件提取到一个新文件

Windows Console: Extract specific range of lines from a huge file to a new file

我想从一个巨大的 CSV 文件(约 15GB,600 万行)中提取几千行,从第 X 行到第 Y 行,而不使用大量 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 施加太大压力。

提前致谢!

以下

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 左右 characters/bytes。

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

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

使用变量使其更加灵活。

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