1

I have a text file (list.txt) which is a list filenames that can be simplified as below:
a
b
c
d

I need a "for" loop that does something like below:

set variable1=a  
set variable2=b
do something with variable1 & 2, lets say variable1 + variable2>>output.txt

then restart the loop from the second line:
set variable1=b
set variable2=c
perform the addition>>output.txt

then from the third line:
set variable1=c
set variable2=d etc..
and keep going until the end of my list.txt

It seems batch file has difficulty when handling multiple lines of data within a loop.
Could someone kindly shed some light on this? Thanks in advance.

1
  • Have you written a code or a batch that does this already, but does not work as it should be? Commented Sep 25, 2014 at 1:28

2 Answers 2

1
@ECHO OFF
SETLOCAL
SET "var1="
SET "var2="
FOR /f %%a IN (q26028954.txt) DO (
 CALL SET "var1=%%var2%%"
 SET "var2=%%a"
 IF DEFINED var1 (
  SET /a total=var1+var2
  CALL ECHO %%var1%% + %%var2%% = %%total%%
  )
)

GOTO :EOF

Where q26028954.txt contains

1
4
7
11

Yields

1 + 4 = 5
4 + 7 = 11
7 + 11 = 18

could also be used with delayedexpansion. Note the use of the set /a total - the run-time, not the parse-time values are applied to the calculation.

Sign up to request clarification or add additional context in comments.

Comments

1
@echo off

setlocal disableDelayedExpansion

set "file_to_process=c:\some.txt"
set "line="
for /f "usebackq tokens=* delims=" %%# in ("%file_to_process%") do (
    setlocal enableDelayedExpansion
    if "!line!" NEQ "" (
        echo do something with !line! and %%#
    )
    endlocal & set "line=%%#"

)

endlocal

Change the path to your file.

2 Comments

Thank you too npocmaka. I don't quite understand your method as I don't see the two variables. Will give it another go when I got chance. :)
@Alan - Do you mean it does not work? Because it works for me (and should be pretty fast too as it does not use subroutines)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.