Print

A for loop within a for loop in MS-DOS

What?
A quick note for myself as I'd forgotten how to do this (we're talking technology belonging to the 90s - MS-DOS v6.22). The example wants to loop through a directory and then loop through the line it finds.

Why?
I use another technology for automation but sometimes the simpler solution is the one I make for other people to use. Explaining MS-DOS batch programs is a lot easier and colleagues trust these more than my all-in-one GUI applications.

How?
Note: we're using the code in a DOS Batch program so our variables have to be prefixed with a double-percent rather than just the one:
copyraw
-- the following loops through directory for any file beginning with Reference
FOR %%A IN ('DIR InitializingFile*') DO ECHO %%A

-- yields:
InitializingFile_123.csv
InitializingFile_456.csv


-- the following loops through directory and separates by underscores
FOR /F "tokens=2,3* delims=_" %%A IN ('DIR InitializingFile*') DO ECHO %%A

-- yields:
123.csv
456.csv
  1.  -- the following loops through directory for any file beginning with Reference 
  2.  FOR %%A IN ('DIR InitializingFile*') DO ECHO %%A 
  3.   
  4.  -- yields: 
  5.  InitializingFile_123.csv 
  6.  InitializingFile_456.csv 
  7.   
  8.   
  9.  -- the following loops through directory and separates by underscores 
  10.  FOR /F "tokens=2,3* delims=_" %%A IN ('DIR InitializingFile*') DO ECHO %%A 
  11.   
  12.  -- yields: 
  13.  123.csv 
  14.  456.csv 
So that's our first loop, here's what the second loop should do:
copyraw
-- the following loops through a line and separates by period (.)
FOR /F "tokens=1,2* delims=." %%I IN ('DIR InitializingFile*') DO ECHO %%I

-- yields:
InitializingFile_123
InitializingFile_456
  1.  -- the following loops through a line and separates by period (.) 
  2.  FOR /F "tokens=1,2* delims=." %%I IN ('DIR InitializingFile*') DO ECHO %%I 
  3.   
  4.  -- yields: 
  5.  InitializingFile_123 
  6.  InitializingFile_456 
Combining the two above FOR statements:
copyraw
FOR /F "tokens=2,3* delims=_" %%A IN ('DIR InitializingFile*') DO FOR /F "tokens=1,2* delims=." %%I IN ('ECHO %%A') DO ECHO %%I

-- yields:
123
456
  1.  FOR /F "tokens=2,3* delims=_" %%A IN ('DIR InitializingFile*') DO FOR /F "tokens=1,2* delims=." %%I IN ('ECHO %%A') DO ECHO %%I 
  2.   
  3.  -- yields: 
  4.  123 
  5.  456 

So Job done. Chances are you need to use this variable a little more:
copyraw
@ECHO OFF
FOR /F "tokens=2,3* delims=_" %%A IN ('DIR InitializingFile*') DO FOR /F "tokens=1,2* delims=." %%I IN ('ECHO %%A') DO (
	ECHO %%I
	GOTO 1
)
:1
ECHO Done.


-- yields:
123
Done.
  1.  @ECHO OFF 
  2.  FOR /F "tokens=2,3* delims=_" %%A IN ('DIR InitializingFile*') DO FOR /F "tokens=1,2* delims=." %%I IN ('ECHO %%A') DO ( 
  3.      ECHO %%I 
  4.      GOTO 1 
  5.  ) 
  6.  :1 
  7.  ECHO Done. 
  8.   
  9.   
  10.  -- yields: 
  11.  123 
  12.  Done. 
Category: MS-DOS :: Article: 524