substring
%varName:~s,l%
extracts the substring starting at character s
with length l
.
In order to include the first character, s
must be 0
.
@echo off
set tq84_var=0123456789
set pos_5_through_eight=%tq84_var:~5,3%
echo pos_5_through_eight = %pos_5_through_eight%
The script prints:
pos_5_through_eight = 567
There is also a variant where only one parameter is specified (%VarName:~s
). If s
is negative, it returns the last s
characters of %VarName%
, otherwise, it removes the first s
characters:
@echo off
set tq84_var=abcdefghijklmnopqrstuvwxyz
set without_first_five_characters=%tq84_var:~5%
set last_five_characters=%tq84_var:~-5%
echo Alphabet without first five characters: %without_first_five_characters%
echo Last five characters of alphabet: %last_five_characters%
C:\> alphabet.bat
Alphabet without first five characters: fghijklmnopqrstuvwxyz
Last five characters of alphabet: vwxyz
Path expansion for batch file arguments
@echo off
echo %%0 %0
echo Drive: %~d0%
echo Path without drive: %~p0%
echo Drive and path: %~dp0%
echo Path with drive: %~f0%
echo Filename without suffix: %~n0%
echo Suffix (incl. dot): %~x0%
echo Short name: %~s0%
echo Attributes: %~a0%
echo Last modification: %~t0%
echo File size: %~z0%
When executed, this
batch file might print something like:
%0 pathExpansion.bat
Drive: C:
Path without drive: \Users\r.nyffenegger\personal\cmd.exe\
Drive and path: C:\Users\r.nyffenegger\personal\cmd.exe\
Path with drive: C:\Users\r.nyffenegger\personal\cmd.exe\pathExpansion.bat
Filename without suffix: pathExpansion
Suffix (incl. dot): .bat
Short name: C:\Users\R508A~1.NYF\personal\cmd.exe\PATHEX~2.BAT
Attributes: --a------
Last modification: 25.02.2019 12:54
File size: 407