Check if Windows batch variable starts with a specific string

38,494

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

Share:
38,494
Admin
Author by

Admin

Updated on August 01, 2020

Comments

  • Admin
    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
    Admin about 9 years
    And 0,3% means it searches for the first 3 letters?
  • jeb
    jeb about 9 years
    No, it gets the first three characters from the variable. Then the first characters are compared with "abc"
  • Bacon Bits
    Bacon Bits about 9 years
    @EricRösch It's a substring. It means "Starting with character 0 (the first) give me 3 characters".
  • Admin
    Admin about 9 years
    Thank you, that's what I wanted to know.
  • kxr
    kxr almost 7 years
    Is 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
    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
    Jesse Chisholm almost 6 years
    And %~dp0 gives just the drive and path, without the filename of the current batch file.
  • vikyd
    vikyd over 5 years
    But sometimes I don't know the length