Filename parsing in batch file and more idiomsTag(s): Misc Prog HowTo
In the following examples, we iterate a list of files and use the idiom ~[idiom] to extract certain part of a given filename.
Extract the filename without the extension : ~n
for %i in (*.*) do echo %~ni
Extract the file extension without the filename : ~x
for %i in (*.*) do echo %~xi
Extract the file attribute : ~a
for %i in (*.*) do echo %~ai
Extract the file time : ~t
for %i in (*.*) do echo %~ti
Extract the drive only : ~d
for %i in (*.*) do echo %~di
Extract the path only : ~p
for %i in (*.*) do echo %~pi
Extract the complete name : ~s
for %i in (*.*) do echo %~si
Extract the file length (in bytes) : ~z
for %i in (*.*) do echo %~zi
%~$PATH:i searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string.
for %i in (java.exe) do @echo. %~$PATH:i
To remove quotes
>for %i in ("real'howto") do @echo. %i "real'howto" >for %i in ("real'howto") do @echo. %~i real'howto
The path (with drive) where the script is : ~dp0
set BAT_HOME=%~dp0 echo %BAT_HOME% cd %BAT_HOME%
The path (without drive) where the script is : ~p0
set BAT_HOME=%~p0 echo %BAT_HOME% cd %BAT_HOME%
The drive where the script is : ~d0
set BAT_DRIVE=%~d0 echo %BAT_DRIVE%
The complete script name : ~s0
set BAT_PATH=%~s0 echo %BAT_PATH%
The script name only (as called with or without the extension): %0
set BAT_NAME=%0 echo %BAT_NAME%