36

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.

ruffin
  • 13,513
  • 8
  • 72
  • 118

2 Answers2

55

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.

Bacon Bits
  • 26,878
  • 5
  • 51
  • 60
  • And 0,3% means it searches for the first 3 letters? –  Apr 15 '15 at 16:53
  • No, it gets the first three characters from the variable. Then the first characters are compared with "abc" – jeb Apr 15 '15 at 17:20
  • 2
    @EricRösch It's a substring. It means "Starting with character 0 (the first) give me 3 characters". – Bacon Bits Apr 15 '15 at 17:21
  • Thank you, that's what I wanted to know. –  Apr 17 '15 at 12:47
  • 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. – kxr May 07 '17 at 12:14
  • 1
    @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](https://ss64.com/nt/syntax-replace.html). – Bacon Bits May 08 '17 at 13:58
  • 1
    But sometimes I don't know the length – vikyd Sep 11 '18 at 12:55
3

to find batch file location use %0 (gives full patch to current batch file) or %CD% variable which gives local directory

rostok
  • 1,826
  • 1
  • 13
  • 20