Search code examples
windowscsvbatch-filebatch-processingbatch-rename

How to Write a batch script for checking mulitple folders and folder inside a folder and set the csv files to variables?


I have to write a batch script to go inside multiple folders and folder inside a folder and set the CSV files inside it and set it to a variable.

my folder structure is

c:\data\client1\data1.csv
c:\data\client1\data2.csv
c:\data\client1\config\env.csv

c:\data\client2\data1.csv
c:\data\client2\data2.csv
c:\data\client2\config\env.csv

so like these I have many clients folder with config folder inside it and some data CSV's

now I have to use some loops to go inside "c:\data\" and check the client1 folder and inside I need to set var = data1.csv and var = data2.csv using for loop then I need to go inside config folder and set envs= env.csv (i.e the file name or path of the files)

I have tried a code but I am not getting the correct login on how to search and loop inside.

@ECHO OFF & setlocal EnableDelayedExpansion
CD "C:\data"
For /R %%A in (*.csv) DO (
  Set "file[!#!]=%%A"
  Set /A #+=1
  )
For /L %%B in (0,1,!#!) do Echo(!file[%%B]!

I modified the code as per the solution. But now I am unable to set the data1.csv in the client1 folder. and Can anyone explain this code? Can anyone help me with the logic of the coding part?

output is :

c:\data\client1\data2.csv
c:\data\client1\config\env.csv
c:\data\client2\data1.csv
c:\data\client2\data2.csv
c:\data\client2\config\env.csv

Solution

  • You can do the following to assign them to an indexed variable. With even moderately large file sets, a singular variable would exceed the line capacity, losing information assigned to it.

    @ECHO OFF & setlocal EnableDelayedExpansion
    CD "C:\data\client"
    For /R %%A in (*.csv) DO (
        Set "file[!#!]=%%A"
        Set /A #+=1
    )
    For /L %%B in (0,1,!#!) do Echo(!file[%%B]!