string 在 for 循环中获取令牌的子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8648178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting substring of a token in for loop?
提问by Ray Cheng
I have this for
loop to get a list of directory names:
我有这个for
循环来获取目录名称列表:
for /d %%g in (%windir%\Assembly\gac_msil\*policy*A.D*) do (
echo %%g
)
Output:
输出:
C:\WINDOWS\Assembly\gac_msil\policy.5.0.A.D
C:\WINDOWS\Assembly\gac_msil\policy.5.0.A.D.O
C:\WINDOWS\Assembly\gac_msil\policy.5.20.A.D.O
C:\WINDOWS\Assembly\gac_msil\policy.5.25.A.D.O
C:\WINDOWS\Assembly\gac_msil\policy.5.35.A.D.O
C:\WINDOWS\Assembly\gac_msil\policy.5.55.A.D.O
C:\WINDOWS\Assembly\gac_msil\policy.5.60.A.D.O
C:\WINDOWS\Assembly\gac_msil\policy.5.70.A.D.O
C:\WINDOWS\Assembly\gac_msil\policy.6.0.A.D.O
I want to get the folder names starting with "policy" but echo %%g:~29
doesn't work.
I also tried to set x=%%g
and then echo %x:~29%
and still doesn't work.
我想获取以“policy”开头的文件夹名称,但echo %%g:~29
不起作用。我也试过set x=%%g
,然后echo %x:~29%
仍然不起作用。
So, how do I get substring from token in for
loop?
那么,如何在for
循环中从令牌中获取子字符串?
回答by Aacini
Of course that set x=%%g
and a substring extraction of x should work, but be aware that if the substring is taken inside a FOR loop, it must be done with ! instead of % (Delayed Expansion):
当然,set x=%%g
x 的子字符串提取应该可以工作,但请注意,如果子字符串是在 FOR 循环中获取的,则必须使用 ! 而不是 %(延迟扩展):
setlocal EnableDelayedExpansion
for /d %%g in (%windir%\Assembly\gac_msil\*policy*A.D*) do (
set x=%%g
echo !x:~29!
)
回答by Aacini
On the other hand, if you want to know "How to get the last part (name and extension) of a token in for loop", the answer is: use the ~Name and ~eXtension modifiers in %%g replaceable parameter:
另一方面,如果您想知道“如何在 for 循环中获取令牌的最后一部分(名称和扩展名)”,答案是:在 %%g 可替换参数中使用 ~Name 和 ~eXtension 修饰符:
for /d %%g in (%windir%\Assembly\gac_msil\*policy*A.D*) do (
echo %%~NXg
)
回答by ChrisWue
A simple
一个简单的
dir /B %windir%\Assembly\gac_msil\*policy*A.D*
should do the trick. If you want to loop over it:
应该做的伎俩。如果你想循环它:
for /f %%g in ('dir /B %windir%\Assembly\gac_msil\*policy*A.D*') do (
echo %%g
)
回答by GuntherPACA
You MUST use setlocal EnableDelayedExpansion
and !variable!
instead of %variable%
, so :
您必须使用setlocal EnableDelayedExpansion
and!variable!
而不是%variable%
,所以:
setlocal EnableDelayedExpansion
for /d %%g in (%windir%\Assembly\gac_msil\*policy*A.D*) do (
set x=%%g
echo !x:~29!
)