PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 22, 2022

[FIXED] Why don't substrings work with command line arguments?

 August 22, 2022     batch-file, environment-variables, string, variables, windows     No comments   

Issue

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?


Solution

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.



Answered By - Mofi
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing