windows 批量字符串连接

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

Batch String Concatenation

windowsbatch-filecmd

提问by NewQueries

I am trying to create a batch string like this: >abcd_

我正在尝试创建一个这样的批处理字符串: >abcd_

I have a variable called soeid, with value as abcd. So this is what i am doing, but it does not work.

我有一个名为 soeid 的变量,其值为 abcd。所以这就是我正在做的,但它不起作用。

set soeid=abcd

set "val1=>"
set "val2=_"
set "str=%val1%%soeid%%val2%"

echo %str%

回答by dbenham

I'm sure it is working just fine. To prove it, add SET STRafter you define the value, and you will see the correct value.

我确定它工作得很好。为了证明这一点,SET STR在定义值后添加,您将看到正确的值。

The problem you are having is when you try to echo the value, the line that is executing becomes: echo >abcd_. The >is not quoted or escaped, so it is simply taking the ouput of ECHO with no arguments and redirecting it to a file named "abcd_"

您遇到的问题是当您尝试回显该值时,正在执行的行变为:echo >abcd_。在>没有加引号或转义,所以它是简单地把ECHO的输出中不带任何参数,并将其重定向到一个名为“abcd_”文件

If you don't mind seeing quotes, then change your line to echo "%str%"and it will work.

如果您不介意看到引号,请将您的行更改为echo "%str%",它会起作用。

The other option is to enable and use delayed expansion (I'm assuming this is a batch script code, and not executing on the command line)

另一个选项是启用和使用延迟扩展(我假设这是一个批处理脚本代码,而不是在命令行上执行)

setlocal enableDelayedExpansion
set soeid=abcd

set "val1=>"
set "val2=_"
set "str=%val1%%soeid%%val2%"

echo !str!

Normal %var%expansion occurs early on while the interpreter is parsing the line. Delayed !var!expansion occurs at the end just before it is executed. The redirection is detected somewhere in the middle. That is why the normal expansion doesn't work - the interpreter sees the expanded >character and interprets it as the output redirection operator. The delayed expansion hides the >character from the interpreter until after redirection is parsed.

正常%var%扩展发生在解释器解析行的早期。延迟!var!扩展发生在它执行之前的最后。在中间的某个地方检测到重定向。这就是正常扩展不起作用的原因 - 解释器看到扩展>字符并将其解释为输出重定向运算符。延迟扩展>对解释器隐藏字符,直到解析重定向之后。

For more info about delayed expansion, type SET /?from the command line and read starting with the paragraph that starts with "Finally, support for delayed environment variable expansion...".

有关延迟扩展的更多信息,请SET /?从命令行键入并阅读以“最后,支持延迟环境变量扩展...”开头的段落。