Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read 2 consecutive lines of a text file and save them as temporary variables

I have files with an ID, model, and date. the files have a format similar to 10000_9999-99_10-01-2011.zip (where 10000 is the ID, 9999-99 is the model, and of course 10-01-2011 is the date).

I would like to modify the dates of these files, but maintain the interval between sessions with the same ID. For example, if 2 sessions had the dates 1/1/2011 and 2/1/2011, and I wanted to update the last session date to 8/1/2012, the first session would have the date 7/1/2012.

Currently my code looks like this:

@echo off
setlocal enabledelayedexpansion
del filedates.txt
FOR /F "tokens=1,2,3,4,5 delims=_" %%a in (filenames.txt) do @echo %%c >>filedates.txt
FOR /F "tokens=1,2,3 delims=-" %%a in (filedates.txt) do (
  echo %%a%%b
)

The output is similar to this (YearMonth):

201107
201109
201204
etc..

I was looking to read a line in filedates.txt, store this date as a variable, then read the next line, and store this as another variable. That way the two variables could be compared to see which is greater, and the process would continue.

like image 779
Jeff K Avatar asked Nov 04 '22 16:11

Jeff K


1 Answers

One straightforward way to do read two lines at a time is to process the lines in the input file one by one with a for /f loop, and "react" only on even numbered lines. Here's a sample code:

@echo off
setlocal enabledelayedexpansion
set evenflag=1
for /f "tokens=*" %%x in (filedates.txt) do set x1=!x2! && set x2=%%x && (
set /a evenflag^^=1 && if !evenflag!==1 (
    rem Do something with !x1! and !x2!
))

Here the variable evenflag is a boolean flag that indicates whether the current line number is even (1 for even lines, 0 to odd lines). x1 and x2 hold the currently read pair of lines.

like image 184
Eitan T Avatar answered Nov 09 '22 10:11

Eitan T