Copy lines from .csv file into another .csv file using batch script

前端 未结 2 1348
日久生厌
日久生厌 2021-01-24 06:38

I am creating .csv files from a device (output) and need to copy a specific number of lines from this file into another .csv file which has the same format.

They are luc

2条回答
  •  有刺的猬
    2021-01-24 07:06

    To illustrate why you don't want to do this in batch, this is the code to copy lines 68 through 107 to another file in VBScript:

    inputFilename  = "C:\path\to\input.csv"
    outputFilename = "C:\path\to\output.csv"
    fromLine = 68
    toLine   = 107
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set inFile  = fso.OpenTextFile(inputFilename)
    Set outFile = fso.OpenTextFile(outputFilename, 2, True)
    
    Do Until inFile.AtEndOfStream Or inFile.Line > toLine
      line = inFile.ReadLine
      If inFile.Line >= fromLine Then outFile.WriteLine line
    Loop
    
    inFile.Close
    outFile.Close
    

    To illustrate why you don't want to do this in VBScript either, this is the same operation in PowerShell:

    $inputFile  = 'C:\path\to\input.csv'
    $outputFile = 'C:\path\to\output.csv'
    $fromLine   = 68
    $toLine     = 107
    
    $skip       = $fromLine - 1
    $numLines   = $toLine - $skip
    
    Get-Content $inputFile | Select-Object -Skip $skip -First $numLines |
        Set-Content $outputFile
    

    which could be simplified to:

    $inputFile  = 'C:\path\to\input.csv'
    $outputFile = 'C:\path\to\output.csv'
    $skip       = 67
    $numLines   = 40
    
    Get-Content $inputFile | Select-Object -Skip $skip -First $numLines |
        Set-Content $outputFile
    

    You can even preserve the CSV header if you want:

    $inputFile  = 'C:\path\to\input.csv'
    $outputFile = 'C:\path\to\output.csv'
    $skip       = 66
    $numLines   = 40
    
    Import-Csv $inputFile | Select-Object -Skip $skip -First $numLines |
        Export-Csv $outputFile -NoType
    

提交回复
热议问题