Check if Windows batch variable starts with a specific string
Solution 1
Use the variable substring syntax:
IF "%variable:~0,3%"=="ABC" [...]
If you need the path to the batch file without the batch file name, you can use the variable:
%~dp0
Syntax for this is explained in the help for the for
command, although this variable syntax extends beyond just the for
command syntax.
Solution 2
to find batch file location use %0
(gives full patch to current batch file) or %CD%
variable which gives local directory
Admin
Updated on August 01, 2020Comments
-
Admin almost 4 years
How can I find out (with Windows a batch command), if, for example, a variable starts with
ABC
?I know that I can search for variables if I know the whole content (
if "%variable%"=="abc"
), but I want that it only looks after the beginning.I also need it to find out where the batch file is located, so if there is a other command that reveals the file's location, please let me know.
-
Admin about 9 yearsAnd 0,3% means it searches for the first 3 letters?
-
jeb about 9 yearsNo, it gets the first three characters from the variable. Then the first characters are compared with "abc"
-
Bacon Bits about 9 years@EricRösch It's a substring. It means "Starting with character 0 (the first) give me 3 characters".
-
Admin about 9 yearsThank you, that's what I wanted to know.
-
kxr almost 7 yearsIs it possible directly on %1 without
set variable=%1
? echo "%1:~0,2" echo "%1:~0,2%" echo "%%1:~0,2%" echo "%%1:~0,2%%" echo "%%%1:~0,2%" echo "%%%1:~0,2%%" echo "%%%%1:~0,2%" : they all don't work. -
Bacon Bits almost 7 years@kxr Not as far as I'm aware. Argument variables don't appear to support substrings, although I believe they do support search and replace.
-
Jesse Chisholm almost 6 yearsAnd
%~dp0
gives just the drive and path, without the filename of the current batch file. -
vikyd over 5 yearsBut sometimes I don't know the length