如何连接 Windows 批处理文件中的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2027070/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:01:44  来源:igfitidea点击:

How to concatenate strings in a Windows batch file?

windowsbatch-filestring-concatenation

提问by Fortega

I have a directory for which I want to list all the .docfiles with a ;.

我有一个目录,我想列出所有.doc带有;.

I know the following batch command echos all the files:

我知道以下批处理命令会回显所有文件:

for /r %%i In (*.doc) DO echo %%i

But now I want to put them all in a variable, add a ;in between and echo them all at once.
How can I do that?

但现在我想把它们都放在一个变量中,;在它们之间添加一个并一次回显它们。
我怎样才能做到这一点?

set myvar="the list: "
for /r %%i In (*.doc) DO <what?>
echo %myvar%

采纳答案by Rubens Farias

What about:

关于什么:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

回答by devio

Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:

基于 Rubens 的解决方案,您需要启用 env 变量的延迟扩展(键入“help setlocal”或“help cmd”),以便在循环中正确评估 var:

@echo off
setlocal enabledelayedexpansion
set myvar=the list: 
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%

Also consider the following restriction (MSDN):

还要考虑以下限制(MSDN):

The maximum individual environment variable size is 8192bytes.

最大单个环境变量大小为 8192 字节。

回答by Pierre

Note that the variables @fnameor @extcan be simply concatenated. This:

请注意,变量@fname@ext可以简单地连接。这个:

forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"

renames all PDF files to "filename_old.pdf"

将所有 PDF 文件重命名为“filename_old.pdf”