Daniella
Daniella

Reputation: 181

Saving Number of Lines in File as a Variable in Batch File

I have this really nice line in my batch file that tells me how many lines are in a file:

 find /v /c "" C:\Users\c1921\mypath\myfolder\!$Unit!.txt

This is nice and gives me 31 for the particular file I'm working with. My problem is the file looks something like this:

 Microsoft (R) Windows Script Host Version 5.8
 Copyright (C) Microsoft Corporation. All rights reserved.

 my_handled
 219278
 check
 219276
 control
 219274

I want to be able to skip the first three lines entirely and then save the first value and then use the second value in my next command etc.

How do I save the number (e.g. 31) into a variable in my batch file?

On a hunch I tried setting a variable like so but it wasn't effective:

set "$testVar="""
echo !$testVar! 

Upvotes: 0

Views: 105

Answers (2)

Aacini
Aacini

Reputation: 67216

This command allows you to "save the number (e.g. 31) into a variable in my batch file":

for /F %%a in ('find /v /c "" ^< C:\Users\c1921\mypath\myfolder\!$Unit!.txt') do set numLines=%%a

This command allows you "to skip the first three lines entirely" and process the rest:

for /F "skip=3 delims=" %%a in (C:\Users\c1921\mypath\myfolder\!$Unit!.txt) do echo Processing: "%%a"

However, in my opinion this problem could be entirely avoided if the three first lines in the text file are supressed from the very beginning. I think this file is generated via a VBScript of JScript program that is executed this way:

cscript progname.vbs > C:\Users\c1921\mypath\myfolder\!$Unit!.txt

The first three lines in the text file may be avoided adding //nologo switch this way:

cscript //nologo progname.vbs > C:\Users\c1921\mypath\myfolder\!$Unit!.txt

Upvotes: 2

Magoo
Magoo

Reputation: 80023

@ECHO OFF
SETLOCAL
SET /a count=3
SET "first="
FOR /f "skip=3delims=" %%a IN (q25089468.txt) DO (
 IF DEFINED first (CALL :show %%a) ELSE (SET "first=%%a")
)

ECHO count=%count%

GOTO :EOF

:show
ECHO first=%first% second=%1
SET /a count+=2
SET "first="
GOTO :eof

I used a file named q25089468.txt containing your data for my testing.

You appear to be asking two entirely different things - how to count the lines and how to skip the first 3, then deliver each succeeding pair to another process.

Upvotes: 1

Related Questions