|
Answer» Hi!
I couldn't find anything posted before, but I'll apologize upfront now if this is a repeat.
I'm trying to find the syntax for extracting specific characters from a string variable within a batch file. For example, I have a variable SET to "123456789" and I wish to use the second and fifth characters in order to create a new variable "52".
tia, Mitch The syntax for extracting a substring is
%variablename:~A,B%
: is a colon ~ is a tilde , is a comma
A and B are numbers or variables.
A is the offset, from the start of the main string, of the first character to EXTRACT. (0 means the first character, 1 means the second character and so on)
B is the number of characters to extract
Code: [Select]set string=hello echo %string:~0,2% he
your operation might proceed like this
set string=123456789 set newstring=%string:~1,1%%string:~4,1%
result 25
set newstring=%string:~4,1%%string:~1,1%
result 52
Your question is contradictory because you SAY you want to use the "second and fifth" characters but your example "52" contains the fifth character and then the second character in that order.
Of course within parentheses then delayed expansion and ! are necessary.
Salmon Trout - Thanks so much for the reply and edification.
I didn't mean to be contradictory in my example. I did it that way on purpose so as not to imply order in the usage of the substrings.
Thanks again, MitchFurther notes...
Using this format again, where the substring is %fullstring:~A,B% and A is the offset and B is the number of characters:
A is obligatory, a positive number means count the offset from the start, a negative number means count backwards from the end.
B is optional and if it is omitted, all characters are taken up to the end of the first string.
If B is negative, then the last B characters of the string are omitted
Thus:
If string=123456789
%string:~2% is 3456789
%string:~-2% is 89
%string:~-4% is 6789
%string:~-4,2% is 67
%string:~0,-2% is 1234567
details are in the SET help, visible if you type SET /? at the prompt
Extract:
Code: [Select] %PATH:~10,5%
would expand the PATH environment variable, and then use only the 5 characters that begin at the 11th (offset 10) character of the expanded result. If the length is not specified, then it DEFAULTS to the remainder of the variable value. If either number (offset or length) is negative, then the number used is the length of the environment variable value added to the offset or length specified.
%PATH:~-10%
would extract the last 10 characters of the PATH variable.
%PATH:~0,-2%
would extract all but the last 2 characters of the PATH variable.
|