Get filename in batch for loop

2019-01-16 16:05发布

问题:

I have the following For loop in a batch file:

for /R c:\test\src %%i IN (*.*) DO (
MOVE %%i C:\test\destination
ECHO %%i
exit
)

The result of the ECHO outputs the entire file path Ex: C:\Foldername\Filename I need to ECHO out only the Filename.Is there a specific command which would give me the filename ? Thanks !

回答1:

When Command Extensions are enabled (Windows XP and newer, roughly), you can use the syntax %~nF (where F is the variable and ~n is the request for its name) to only get the filename.

FOR /R C:\Directory %F in (*.*) do echo %~nF

should echo only the filenames.



回答2:

or Just %~F will give you the full path and full file name.

For example, if you want to register all *.ax files in the current directory....

FOR /R C:. %F in (*.ax) do regsvr32 "%~F"

This works quite nicely in Win7 (64bit) :-)



回答3:

I am a little late but I used this:

dir /B *.* > dir_file.txt

then you can make a simple FOR loop to extract the file name and use them. e.g:

for /f "tokens=* delims= " %%a in (dir_file.txt) do (
gawk -f awk_script_file.awk %%a
)

or store them into Vars (!N1!, !N2!..!Nn!) for later use. e.g:

set /a N=0
for /f "tokens=* delims= " %%a in (dir_file.txt) do (
set /a N+=1
set v[!N!]=%%a
)


回答4:

If you want to remain both filename (only) and extension, you may use %~nxF:

FOR /R C:\Directory %F in (*.*) do echo %~nxF