1

So I'm currently writing a batch script that will generate a file based on a folder name. The main issue I'm stuck with is returning a string within my path when it contains a certain substring. To elaborate: The path I'm currently looking at:

someOtherFolders\Project_Banana\05_Processing\05_Logs

Now what I will need to get is "Project_Banana". The only thing that's always fixed with this string is that it starts with "Project_" but everything else in the folder structure can differentiate (being the actual project name "Banana" in this case, where the folder is located in the path,etc.).

Only things I found were related to findstr and would just return true or false, but that's not what I want.

1 Answer 1

0

Below is a good starting point using a batch script with a FOR loop simply echoing the path example as per your question and using batch variable substrings accordingly. You can easily replace the ECHO command within the loop with a DIR command to list the directories if that's what you need; just adjust the TOKEN number accordingly and test. You can replace the ECHO !str! with whatever other command(s) you need the script to process.

Batch Script 1

@ECHO ON
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /F "TOKENS=2 DELIMS=\" %%F IN ('ECHO someOtherFolders\Project_Banana\05_Processing\05_Logs') DO (
    SET prjStr=%%~F 
    SET str=!prjStr:Project_=!
    ECHO !str! 
)

GOTO EOF

Result

Banana

Batch Script 2

@ECHO ON

SET SRC1=C:\Users
SET SRC2=Documents

FOR /D %%X IN ("%SRC1%\*") DO FOR /D %%Y IN ("%%X\%SRC2%\*") DO ECHO %%~Y
GOTO EOF

Potentially Helpful

@ECHO ON

::SETLOCAL ENABLEDELAYEDEXPANSION
SET DIR=C:\Users
FOR /F %%F IN ('DIR /B /AD "%DIR%"') DO (
    SET fldName=%%~F
    SET SRC1=C:\Users\%fldName%
    SET SRC2=Documents
FOR /D %%X IN ("%SRC1%") DO FOR /D %%Y IN ("%%X\%SRC2%\*") DO ECHO %%~FPY
)
GOTO EOF

Further Resources

1
  • Hi Walmart, is it possible it just extracts the second folder from the path? When I run it from: C:\Users\XXXXXXX\Documents\XXXXXX\01 - FTS\Project_Default\05_Processing it returns "Users"? Feb 15, 2017 at 15:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .