如何连接变量在批处理文件字符串或变量 [英] How to concatenate variable with string or variable in batch file
问题描述
我想串联的一个变量的字符串。
在第7行到第11行我尝试Concat的!somevariable!用字符串或%% P个变量。
但是,这似乎并没有工作。
即。您当前文件夹文件0_1_en.pdf。
脚本快捷文件到第1位的名称。
后来我想创建的字符串,例如一个新的变量:结果GEN 0,其中0是!sPDFName!
完成code:
1 SETLOCAL EnableDelayedExpansion
2 / Fdelims =在('DIR / B的* .pdf')%% P做(
3 SETsPDFName = %%〜恩智浦
4回声!sPDFName:0,1〜!
5如果sPDFName:!〜0,1==1(SETsPDFName = sPDFName:!〜0,1)
6如果sPDFName:!〜0,1==0(SETsPDFName = sPDFName:!〜0,1)
7 SET tempStr = GEN!sPDFName!
8 SET MYVAR =!MYVAR! %% P
9
10回声%MYVAR%
11回声%tempStr%
12 ::回声!sPDFName!
13暂停
在14 / Fdelims =%% H('DIR / B *。html的')做(
15 IFsPDFName:!〜-0==!%% H:〜0,1!回声%% ^ h
16)
17)
级联的作品!但是,你的回音失败。
当你在一个命令块(括号)块将会被执行之前的所有%的变量被扩展,所以输出回声%MYVAR%
是进入for循环之前MYVAR的内容。
但是,你知道正确的方式已经,使用延迟扩展(与!
)
所以你的code应该像
SETLOCAL EnableDelayedExpansion
FOR / Fdelims =%%的('DIR / B的* .pdf')芘做(
SETsPDFName = %%〜恩智浦
回声sPDFName:〜!0,1!
IF!sPDFName:〜!0,1==1(SETsPDFName = sPDFName:!〜0,1)
IF!sPDFName:〜!0,1==0(SETsPDFName = sPDFName:!〜0,1)
SET tempStr = GEN!sPDFName!
SET MYVAR =!MYVAR! %% P 回声!myvar的!
回声!tempStr!
::回声!sPDFName!
暂停
FOR / Fdelims =%%的H('DIR / B *。html的')做(
IFsPDFName:!〜-0==!%% H:〜0,1!回声%% ^ h
)
)
I would like to concatenate a variable with a string.
In line 7 to line 11 I try to concat !somevariable! with a string or with %%P variable.
But this does not seem to work.
I.e. you have file 0_1_en.pdf in current folder.
The script shortcuts the name of file to first digit.
Afterwards I want to create a new variable with a string for example:
"GEN 0" where 0 is the !sPDFName!
Complete code:
1 SETLOCAL EnableDelayedExpansion
2 for /f "delims=" %%P in ('dir /b *.pdf') do (
3 SET "sPDFName=%%~nxP"
4 echo "!sPDFName:~0,1!"
5 IF "!sPDFName:~0,1!"=="1" (SET "sPDFName=!sPDFName:~0,1!")
6 IF "!sPDFName:~0,1!"=="0" (SET "sPDFName=!sPDFName:~0,1!")
7 SET tempStr=GEN !sPDFName!
8 SET myvar=!myvar! %%P
9
10 echo "%myvar%"
11 echo "%tempStr%"
12 ::echo "!sPDFName!"
13 pause
14 for /f "delims=" %%H in ('dir /b *.html') do (
15 IF "!sPDFName:~-0!"=="!%%H:~0,1!" echo %%H
16 )
17 )
The concatenation works! But your echo fails.
As you are in a command block (parenthesis) all percent variables are expanded before the block will be executed, so the output of echo "%myvar%"
is the content of myvar before entering the FOR-Loop.
But you know the correct way already, using the delayed expansion (with !
)
So your code should look like
SETLOCAL EnableDelayedExpansion
for /f "delims=" %%P in ('dir /b *.pdf') do (
SET "sPDFName=%%~nxP"
echo "!sPDFName:~0,1!"
IF "!sPDFName:~0,1!"=="1" (SET "sPDFName=!sPDFName:~0,1!")
IF "!sPDFName:~0,1!"=="0" (SET "sPDFName=!sPDFName:~0,1!")
SET tempStr=GEN !sPDFName!
SET myvar=!myvar! %%P
echo "!myvar!"
echo "!tempStr!"
::echo "!sPDFName!"
pause
for /f "delims=" %%H in ('dir /b *.html') do (
IF "!sPDFName:~-0!"=="!%%H:~0,1!" echo %%H
)
)
这篇关于如何连接变量在批处理文件字符串或变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!