Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Batch: Read only the filename from a variable with path and filename

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).

like image 615
Michael Avatar asked Jan 18 '09 04:01

Michael


People also ask

What does && do in batch file?

&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).

What is %% K in batch file?

So %%k refers to the value of the 3rd token, which is what is returned.

What is path in batch file?

The PATH is an environment variable containing a list of directories, separated by semi-colons (;). It is used by the command processor to find the programs or executables it needs. The PATH variable can be set in two ways: SET PATH=c:\bat;c:\dos. or: PATH c:\bat;c:\dos.


2 Answers

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%
like image 95
Dave Ray Avatar answered Oct 08 '22 00:10

Dave Ray


Slightly improved version :

set FILENAME="%~nx1"

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

like image 35
Cyan Avatar answered Oct 07 '22 22:10

Cyan