7

I am currently looking for a way to take a variable in batch and only parse out the filename.

For example, I pass my batch file a -s parameter from another application which is subsequently set to my source variable. The source file variable typically contains something like: C:\Program Files\myapp\Instance.1\Data\filetomove.ext.

I assume to read from the end of the variable until the first "\" and set the result to a new variable filename but I have not been able to use the "for /f" commmand successfully.

Any help would be much appreciated!

Update: Only standard XP or Windows 2000/2003 available...(can't assume resource kits installed).

2 Answers 2

9

If its coming in as an argument to the script, i.e. %1, %2, etc, you can extract just the filename and extension into a variable like this:

set FILENAME=%~nxN

where N is the index of the argument. For example, this script will echo just the filename of the first argument:

@echo off
set FILENAME=%~nx1
echo %FILENAME%
4
  • Thank you! I was re-reading the help and was over complicating the %~nxI instructions. Thanks!!!!
    – Michael
    Commented Jan 18, 2009 at 4:59
  • Yeah. Those instructions are really pretty sucky, if you're lucky enough to even find them.
    – Dave Ray
    Commented Jan 18, 2009 at 5:01
  • +1 was about to ask this, SO has a great duplicate question detector :-)
    – Wim Coenen
    Commented Mar 5, 2009 at 0:17
  • 2
    Unfortunately, this instruction seems broken if there is an "&" character inside the name. I just had the problem with a directory called "NGC&Wii". Obviously, one can change the name, but in some situations, you may not be allowed to change it.
    – Cyan
    Commented Oct 27, 2011 at 23:13
2

Slightly improved version :

set FILENAME="%~nx1"

The extra parenthesis will ensure that special characters, such as '&', will not interfere during batch execution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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