Jump to Real's How-to Main page

Filename parsing in batch file and more idioms

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  

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%

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2007
[ home ]