Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split path and take last folder name in batch script

I want to split the string (having a path) with \and take last folder name in a variable. Please help.

e.g
mypath=D:\FOLDER1\FOLDER2\FOLDER3\

I want FOLDER3 in a variable.

I tried with the command below which is working if the the last character is not \ :

for %f in (C:\FOLDER1\FOLDER2\FOLDER3) do set myfolder=%~nxf 

It is not working if the last character is \

Also it is not working if variable is used like : for %f in (%mypath%) do set myfolder=%~nxf

like image 594
user2013 Avatar asked Jun 24 '13 15:06

user2013


People also ask

What is @echo off in batch script?

batch-file Echo @Echo off @echo off prevents the prompt and contents of the batch file from being displayed, so that only the output is visible. The @ makes the output of the echo off command hidden as well.

What is %% A in batch script?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

What is %% g'in batch file?

%%parameter : A replaceable parameter: in a batch file use %%G (on the command line %G) FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or 'tokens'.

What does %1 mean in a batch file?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.


1 Answers

@echo off  set MYDIR=C:\FOLDER1\FOLDER2\FOLDER3\ set MYDIR1=%MYDIR:~0,-1%  for %%f in (%MYDIR1%) do set myfolder=%%~nxf echo %myfolder% 

outputs

FOLDER3 
like image 135
user93353 Avatar answered Oct 11 '22 09:10

user93353