Saturday, November 14, 2009

Cutting Characters in Batch Scripts

It's necessary sometimes to cut some characters from the value of a variable in a batch script. For example, you need to rename a file having a too long name, or need to pass a certain string as a parameter for another batch file and need to cut last 5 characters. How can you cut these characters from a string? There is really simple solution provided by the command interpreter. For example, if you want to cut last ten characters from the first parameter given to your batch file, use the following code:
SET param1=%1%
SET param2=%param1
:~0,-10%
In general, to cut a string from a variable, you should use one of the following constructions:
%var:~n,m%
%var:~n,-m%
%var:~n%

The first line cuts m characters from the string assigned to variable var, starting with n-th character (beginning from zero). The second line removes m characters from the string's tale. The third one cuts all characters in the string beginning with n-th character.

No comments:

Post a Comment

Translate