Wednesday, 27 June 2018

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


I have a text file A.txt


Pinging [xx.xx.xx.xx] with 32 bytes of data:

Request timed out.

Ping statistics for xx.xx.xx.xx:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss)

I would like to copy the first 2 lines of this file into another file B.txt, i.e.


Pinging [xx.xx.xx.xx] with 32 bytes of data:
Request timed out.

I know I can use FOR /F to loop through the lines in the file. I know how to skip the first two lines, but not to only read them. I've also tried to do it by using FOR /F with a DO ECHO and related FIND command and also a straight FINDSTR command (in both cases searching for "Pinging" and "Request") but I cannot get either to work properly.



Answer



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 ^ ^ ^
echo.
echo. Outputs the first ^ lines from ^ to ^.
echo.
:END

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...