JSI Tip 0932. How do I parse a string?.

Use the SET command to parse an environment variable.

The general syntax is:

%var:~pos,len%     where

var is an environment variable that contains a string.

pos is the starting position of the sub-string, starting with 0.

len is the length of the sub-string.

1. To extract the 2nd, 3rd, and 4th character from the 1st parameter of a batch:

      set str=%1
      set pos234=%str:~1,3%
      @echo %pos234%

2. If your user names are always composed of the first initial followed by the last name, you can extract the last name:

      set lastname=%UserName:~1,99%
      @echo %lastname%

      This works because the extraction ends at the length of the variable

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish