这可能已经解决了,但我看起来并没有找到满意的答案。一个如何快速计算.bat脚本中环境变量的长度?
我的问题涉及几千个字符的环境变量(我知道实际限制大约是8k ...命令行的最大大小)。
直接的方法只计算字符数。我将使用%path%作为示例。假设已知环境变量存在 - 它在我的情况下也是如此 - 所以它的长度至少为1.不涉及特殊字符(例如双引号):
@echo off& setlocal enabledelayedexpansion
set /a length=1
:loop
if not "!path:~%length%,1!"=="" set /a length+=1& goto loop
这会计算并保留环境变量' length'中的值。 我见过这样的解决方案,但对于长度较长的变量,它们非常慢。更好的方法(几个数量级更快,更确定)是二进制搜索,例如:
@echo off& setlocal enabledelayedexpansion
set /a p2=16384, length=p2-1
:loop
if "!path:~%length%,1!"=="" set /a length-=p2
if !p2! geq 2 (set /a length+=p2/=2& goto loop) else set /a length+=1
我想我可以忍受这一点,但我仍然想知道我是不是很愚蠢而且遗漏了一些明显的东西。我正在寻找纯粹的.bat解决方案。
下面添加6/12/2017
从Compo建议的this method学习,使我更简单/更快地解决问题,然后使用dostips' (比所有琴弦长度1 .. 8k快18%)。这似乎足以发布:
@echo off& setlocal enabledelayedexpansion
set "str=A%path%"
set length=0
for %%p in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if not "!str:~%%p,1!"=="" set "str=!str:~%%p!"& set /a length+=%%p
)
答案 0 :(得分:0)
@echo off
del temp.txt
for /F "delims=:" %%G in ('findstr /N "<resource>" "%~F0"') do set "start=%%G"
(for /F "usebackq skip=%start% delims=" %%G in ("%~F0") do echo %%G) > temp.txt
rem echo everything after "<resource>" - code by @Aacini
for %%G in (temp.txt) do set /a size=%%~zG - 2
rem get the file length and remove the CR\LF count
echo %size%
pause
exit/b
<resource>
things to test length
and can be mutli-line
此脚本将字符串回显到文件,并使用for循环检索文件大小,即字符串长度。 要最大限度地提高速度,code-golf。
一些事实:
.54
长字符串需要1.04 mb
秒。1.04 MB
字符串的长度比获取1字节长度的字符串更有效。您可以通过调用Powershell来绕过8191字节限制。
echo $characters = "yourString" > temp.ps1
echo $x= $characters.length >> temp.ps1
echo write-host $x >> temp.ps1
powershell -command "C:\PathToPS1file\temp.ps1
del /f /s /q temp.ps1
这是一个缓慢的PowerShell方法,需要大量的转义。