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

Jerold Schulman

December 18, 1998

1 Min Read
ITPro Today logo in a gray background | ITPro Today

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

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like