How to concatenate variable with string or variable in batch file

怎甘沉沦 提交于 2019-12-30 06:12:09

问题


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 )

回答1:


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
  )
)


来源:https://stackoverflow.com/questions/9349027/how-to-concatenate-variable-with-string-or-variable-in-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!