home
Dos batch file, command line string manipulation
Author Nigel Rivett
For the following create a file with extension .bat, copy the code into the file and run it.
%var:~x,y%
x - start position. zero for first character. minus from end
y - number of characters, mins for exclude at end
set sinp=abcdef
rem all characters from position - position = start
set s1=%sinp:~0%
echo %sinp% %s1%
rem abcdef abcdef
rem all characters from position - position = 1 - remove first character
set s1=%sinp:~1%
echo %sinp% %s1%
rem abcdef bcdef
rem all characters from end - get last character
set s1=%sinp:~-1%
echo %sinp% %s1%
rem abcdef f
rem all characters from end - get last two characters
set s1=%sinp:~-2%
echo %sinp% %s1%
rem abcdef ef
rem 3 characters staring with 3rd
set s1=%sinp:~2,3%
echo %sinp% %s1%
rem abcdef cde
rem start with 2nd character, exclude last 2
set s1=%sinp:~1,-2%
echo %sinp% %s1%
rem abcdef bcd
rem add a backslash to end if last character is not a backslash
set sinp=abcdef
if not %sinp:~-1% == \ (set s1=%sinp%\) else set s1=%sinp%
echo %sinp% %s1%
rem abcdef abcdef\
set sinp=abcdef\
if not %sinp:~-1% == \ (set s1=%sinp%\) else set s1=%sinp%
echo %sinp% %s1%
rem abcdef\ abcdef\
set /p var=press enter
home