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 luckily the same format and so each file has the same lines to copy over (line 68 to 107). I have had a go at this using code from other sources but all I have been able to do so far is to copy out the data but am unable to insert it into the other file. Any help would be great!
@echo off
Set "InputFile=C:\*****\Desktop\Dev\Test\Default.csv"
Set "OutPutFile=C:\*****\Desktop\Dev\Test\OutputData.csv"
Set FromLine=68
Set ToLine=107
Call:ExtractLinesFromTextFile "%InputFile%" %FromLine% %ToLine% >
"%OutPutFile%"
Exit /b
:ExtractLinesFromTextFile <InputFile> <FromLine> <ToLine>
(
echo Wscript.echo(ExtractLinesFromTextFile("%~1",%2,%3^)^)
echo Function ExtractLinesFromTextFile(TextFile,FromLine,ToLine^)
echo If FromLine ^<= ToLine Then
echo With CreateObject("Scripting.FileSystemObject"^).OpenTextFile(TextFile^)
echo Do Until .Line = FromLine Or .AtEndOfStream
echo .SkipLine
echo Loop
echo Do Until .Line ^> ToLine Or .AtEndOfStream
echo ExtractLinesFromTextFile = ExtractLinesFromTextFile ^& (.ReadLine ^&
vbNewLine^)
echo Loop
echo End With
echo End If
echo End Function
)>"%~n0.vbs"
Cscript /Nologo "%~n0.vbs" "%~1" %~2 %~3
If Exist "%~n0.vbs" Del "%~n0.vbs"
Exit /b
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:
To illustrate why you don't want to do this in VBScript either, this is the same operation in PowerShell:
which could be simplified to:
You can even preserve the CSV header if you want:
There is absolutely no need to use a batch file that creates and invokes a VBScript.
You could accomplish the task by a pure batch script like this:
Note that pure batch file solutions may be limited in line lengths and file sizes. The aforementioned approach cannot handle lines longer than 1023 bytes and files with more than 2147483647 lines.
Here is another but slower pure batch script solution:
This approach cannot handle lines longer than 8191 - 7 = 8184 bytes and files with more than 2147483647 lines.