Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting string after last instance of delimiter in a Batch file

I'm working on writing a Windows batch file that is called by a Java program. A number of different strings denoting file directories are passed into the batch file as parameters. I am trying to figure out how to extract a string after the last instance of the "\". For example, I have three directories:

C:\Users\owner\Documents
C:\Users\owner\Videos
C:\Users\owner\Pictures\Trip

I would like to split it so that the strings become:

Documents
Videos
Trip

How would you guys suggest I do this?

EDIT: A follow-up question has been asked here: For loop in Windows batch file: Error: "The syntax of the command is incorrect"

like image 414
DerStrom8 Avatar asked Jan 12 '23 21:01

DerStrom8


2 Answers

After assigned one parameter to "param" variable, use:

for %%a in (%param:\= %) do set lastDir=%%a

This method works as long as the last directory does NOT have spaces. This detail may be fixed, if needed. The processing of all parameters would be like this:

:nextParam
   set "param=%~1"
   if not defined param goto endParams
   for %%a in (%param:\= %) do set lastDir=%%a
   echo Last dir: %lastDir%
   shift
goto nextParam
:endParams

Or, in a simpler way (with no spaces restrictions):

:nextParam
   if "%~1" equ "" goto endParams
   echo Last dir: %~N1
   shift
goto nextParam
:endParams
like image 181
Aacini Avatar answered Feb 02 '23 09:02

Aacini


If the strings are passed as arguments 1-3. you can use %~n1, %~n2, %~n3 to get the last folder in the path.

like image 25
RGuggisberg Avatar answered Feb 02 '23 09:02

RGuggisberg