SpringLearner
SpringLearner

Reputation: 13844

How to split a string and make directories?

I have a string containing some names in comma , separated and I want to make make directories after splitting by comma ,

For example if the string is abc,def,ghi

Then I want to create 3 folders named as abc and def and ghi

I tried like this

@echo off&setlocal 
set "data_set_path=def,ghi,jkl"
REM first split by commas
for /f "tokens=1-4 delims=," %%i in ("%data_set_path%") do set "pc1=%%i"& set "pc2=%%j"& set "pc3=%%k"&set "pc4=%%l"
<nul set/p"=1st split: %pc1% %pc2% %pc2% %pc4%"&echo( 

I can split the string but I do know how to create folders with those names

Upvotes: 1

Views: 169

Answers (1)

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem The easy one
    set "data_set_path=def,ghi,jkl"
    for %%a in (%data_set_path%) do if not exist "%%a" md "%%a"

    rem A more "elaborated" to allow spaces in the folders
    set "data_set_path=first folder,second folder,third folder"
    for %%a in ("%data_set_path:,=","%") do if not exist "%%a" md "%%~a"

As the comma is a delimiter inside for commands, you can just iterate over the variable contents (first option)

If you want to allow for spaces inside the folder names (that are also a delimiter in for commands), a simple trick can be used, iterating over the list with the the commas replaced with "," and the variable quoted, so the value first folder,second folder,third folder is converted to "first folder","second folder","third folder" and then iterated, using the commas as delimiters again but keeping the spaces inside the folder names

This second approach is also needed if the folder names can include other special characters (&, ;, >, <, ...)

Upvotes: 2

Related Questions