There doesn't appear to be an easy way to get the length of a string in a batch file. E.g.,
SET MY_STRING=abcdefg
SET /A MY_STRING_LEN=???
How would I find the string length of MY_STRING
?
Bonus points if the string length function handles all possible characters in strings including escape characters, like this: !%^^()^!
.
As there is no built in function for string length, you can write your own function like so:
This function needs always 13 loops, instead of a simple strlen function which needs strlen-loops.
It handles all characters.
You can do it in two lines, fully in a batch file, by writing the string to a file and then getting the length of the file. You just have to subtract two bytes to account for the automatic CR+LF added to the end.
Let's say your string is in a variable called
strvar
:The length of the string is now in a variable called
strlength
.In slightly more detail:
FOR %%? IN (filename) DO ( ...
: gets info about a fileSET /A [variable]=[expression]
: evaluate the expression numerically%%~z?
: Special expression to get the length of the fileTo mash the whole command in one line:
If you are on Windows Vista +, then try this Powershell method:
or alternatively:
I'm on Windows 7 x64 and this is working for me.
Just found ULTIMATE solution:
The output is:
It handles escape characters, an order of magnitude simpler then most solutions above, and contains no loops, magic numbers, DelayedExpansion, temp files, etc.
In case usage outside batch script (mean putting commands to console manually), replace
%%RESULT%%
key with%RESULT%
.If needed,
%ERRORLEVEL%
variable could be set toFALSE
using any NOP command, e.g.echo. >nul
I want to preface this by saying I don't know much about writing code/script/etc. but thought I'd share a solution I seem to have come up with. Most of the responses here kinda went over my head, so I was curious to know if what I've written is comparable.
It's Much Simplier!
Pure batch solution. No temp files. No long scripts.
1000
is the maximum estimated string lenght. Change it based on your needs.