Home > Enterprise >  Why doesn't substrings work with command line arguments
Why doesn't substrings work with command line arguments

Time:10-06

In a Windows batch file, the following will work to extract all of %1 except the last 4 characters:

set foo=%1
set x=%foo:~,-4%

But this will not work:

set x=%1:~,-4%

Why is this?

CodePudding user response:

The Windows command processor cmd.exe supports string substitutions only with environment variables (and with dynamic variables), but not with batch file arguments (or with loop variables).

foo is an environment variable of which value is referenced with immediate expansion using %foo% and with delayed expansion with !foo!. String substitutions are supported for environment variables as described by the help output on running set /? in a command prompt window. The Windows command processor cmd.exe supports string substitutions on environment (and dynamic) variable expansions everywhere in a command line.

For more details see How does the Windows Command Interpreter (CMD.EXE) parse scripts?

For an explanation of the difference between environment and dynamic variables read the long answer on Difference between Dynamic Environment Variables and Normal Environment Variables in CMD.

%1 references an argument passed to the batch file. The help output on running call /? in a command prompt window explains how arguments can be referenced in a batch file and which modifiers are supported by the Windows command processor. String substitutions are not supported by cmd.exe on argument strings.

For completeness the help output on running for /? explains how a loop variable can be referenced inside the body of a loop and which modifiers are available (the same as for argument references). String substitutions are not support for loop variables.

  • Related