如何在 Windows 批处理文件中连接字符串以进行循环?

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

How to concatenate strings in windows batch file for loop?

windowsbatch-file

提问by Marcus Thornton

I'm familiar with Unix shell scripting, but new to windows scripting.

我熟悉 Unix shell 脚本,但不熟悉 Windows 脚本。

I have a list of strings containing str1, str2, str3...str10. I want to do like this:

我有一个包含 str1、str2、str3...str10 的字符串列表。我想这样做:

for string in string_list
do
  var = string+"xyz"
  svn co var
end

I do found some thread describing how to concatenate string in batch file. But it somehow doesn't work in for loop. So I'm still confusing about the batch syntax.

我确实找到了一些描述如何在批处理文件中连接字符串的线程。但它以某种方式在 for 循环中不起作用。所以我仍然对批处理语法感到困惑。

回答by Endoro

Try this, with strings:

试试这个,用字符串:

set "var=string1string2string3"

and with string variables:

并使用字符串变量:

set "var=%string1%%string2%%string3%"

回答by Ansgar Wiechers

In batch you could do it like this:

批量你可以这样做:

@echo off

setlocal EnableDelayedExpansion

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do (
  set "var=%%sxyz"
  svn co "!var!"
)

If you don't need the variable !var!elsewhere in the loop, you could simplify that to

如果您不需要!var!循环中其他地方的变量,您可以将其简化为

@echo off

setlocal

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do svn co "%%sxyz"

However, like C.B. I'd prefer PowerShell if at all possible:

但是,像 CB 一样,如果可能的话,我更喜欢 PowerShell:

$string_list = 'str1', 'str2', 'str3', ... 'str10'

$string_list | ForEach-Object {
  $var = "${_}xyz"   # alternatively: $var = $_ + 'xyz'
  svn co $var
}

Again, this could be simplified if you don't need $varelsewhere in the loop:

同样,如果您不需要$var循环中的其他地方,这可以简化:

$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }

回答by Ilia S.

A very simple example:

一个非常简单的例子:

SET a=Hello
SET b=World
SET c=%a% %b%!
echo %c%

The result should be:

结果应该是:

Hello World!