且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用批处理脚本将行从.csv文件复制到另一个.csv文件

更新时间:2023-01-30 19:11:39

为说明为什么不想批量执行此操作,这是将68至107行复制到VBScript中另一个文件的代码:

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

为说明为什么您也不想在VBScript中执行此操作,这与PowerShell中的操作相同:

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

可以简化为:

$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

如果需要,您甚至可以保留CSV标头:

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