Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
You might have more joy with this over on SuperUser ( – James Green Mar 13 '11 at 14:38
up vote 3 down vote accepted

Because of your Windows tag, I assume your cmd.exe has extensions built-in. If that is the case, you can use two of FOR'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. See FOR /? for full details.

C:\>SET FSPATH=C:\WINDOWS\Temp\file.txt
C:\>echo %FSPATH%
C:\>FOR /F "delims=|" %A IN ("%FSPATH%") do echo %~nxA

Alternatively, should you not have extensions in your cmd.exe, you can use delims=\, 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:

FOR /F "delims=|" %%A IN ("%FSPATH%") do echo %%~nxA

The %%~nxA variable would then contain the file name and extension and can be used throughout your script.

share|improve this answer
i try it but the following error appear :- SPATH~nxA was unexpected at this time. – Mohammad AL-Rawabdeh Mar 13 '11 at 15:05

Give this a try:

for %f in (A\B\C\D) do set var=%~nxf
share|improve this answer
this error appear :- ~nxf was unexpected at this time. C:\Program Files\GNU\>for ~nxf – Mohammad AL-Rawabdeh Mar 13 '11 at 15:07
@MohammadAL-Rawabdeh: You said "from a command line". If you're doing it in a batch file, you'll need to use double percent signs. – Dennis Williamson Mar 13 '11 at 15:29
sorry ... i want execute it from batch file :- it will be %~nxf% – Mohammad AL-Rawabdeh Mar 13 '11 at 15:46
@MohammadAL-Rawabdeh: No. for %%f in (A\B\C\D) do set var=%%~nxf – Dennis Williamson Mar 13 '11 at 15:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.