Batch File that copies the first 2 lines of a text file into another text file

Solution 1:

I've posted the entire code below, but the real meat is here:

:: set counter
set c=0
for /f "delims=|" %%i in (%1) do (
:: increment counter for each line read
  set /a c=!c!+1
  if !c! leq %3 echo %%i >> %2
)

Basically you set the counter variable c to 0, then increment it for each line read from the text file. You test the counter against the max lines and echo it to the output file if it's less than or equal.

The "delims=|" parameter in the for loop keeps it from breaking the line into tokens at space characters and thus only outputting a partial line. The unusual !c! variable is how to reference variables that are using delayed expansion. If you just used %c%, the value would never change inside the for loop.

You provide the script with three parameters: input file, output file and # of lines to output. The %1,%2 and %3 represent each of these input parameters in the script.

 @echo off

REM ======================================================================
REM
REM NAME: 
REM
REM AUTHOR: Scott McKinney
REM DATE  : 
REM
REM PURPOSE: 
REM COMMENT: 
REM DEPENDENCIES:
REM
REM Revisions:
REM
REM ======================================================================

setlocal ENABLEEXTENSIONS
setlocal ENABLEDELAYEDEXPANSION

set a=%1
if "%1"=="" goto HELP
if "%a:~0,2%"=="/?" goto HELP
if "%a:~0,2%"=="-?" goto HELP
if "%a:~0,2%"=="/h" goto HELP
if "%a:~0,2%"=="/H" goto HELP
if "%a:~0,2%"=="-h" goto HELP
if "%a:~0,2%"=="-H" goto HELP
if "%a:~0,3%"=="--h" goto HELP
if "%a:~0,3%"=="--H" goto HELP

:: set counter
set c=0
for /f "delims=|" %%i in (%1) do (
:: increment counter for each line read
  set /a c=!c!+1
  if !c! leq %3 echo %%i >> %2
)
goto END

:HELP
echo.
echo Usage: %0 ^<input file^> ^<output file^> ^<n lines^>
echo.
echo. Outputs the first ^<n^> lines from ^<input file^> to ^<output file^>.
echo.
:END