How do I store the last part of directory in a variable?
For example I have the following path: A\B\C\D
, I want to store D
in variable like file_name=D
.
How do I store the last part of directory in a variable?
For example I have the following path: A\B\C\D
, I want to store D
in variable like file_name=D
.
Because of your Windows tag, I assume your
cmd.exe
has extensions built-in. If that is the case, you can use two ofFOR
's special substitution variable references:Given a variable
%A
, containing a path and file:%~nA
will output the file name,%~xA
will output the file extension. The following example uses the pipe character|
as a delimiter. The pipe is an invalid character for files and paths and should not appear in a path. This will allow for spaces in paths and filenames. SeeFOR /?
for full details.Alternatively, should you not have extensions in your
cmd.exe
, you can usedelims=\
, count the directory separators and split your path/file string based on that number.Edit: Per your comment about the error. Above is an example on the command line. If you want to perform the same within a batch script, you need to double the
%
on the the variables:To use the value outside of the
FOR
loop, you would need to assign the value to another variable. The variable%%A
is limited to the scope ofFOR
.Give this a try: