Windows Vista批处理(.bat)文件中的长命令分成多行

时间:2020-03-05 18:55:04  来源:igfitidea点击:

如何使长命令遍历Windows(Vista)批处理文件中的多行?

解决方案

回答

只要我们记得插入符和其后的换行符已被完全删除,就可以用插入符^分隔长行。因此,如果我们在换行的地方应该有一个空格,请加上一个空格。 (更多有关以下内容。)

例子:

copy file1.txt file2.txt

将被写为:

copy file1.txt^
 file2.txt

回答

插入符号的规则是:

在行的末尾插入符号,追加下一行,将转义添加行的第一个字符。

我们可以多次使用插入符号,但是完整的行不能超过〜8192个字符(WindowsXP,WindowsVista和Windows7)的最大行长度。

echo Test1
echo one ^
two ^
three ^
four^
*
--- Output ---
Test1
one two three four*

echo Test2
echo one & echo two
--- Output ---
Test2
one
two

echo Test3
echo one & ^
echo two
--- Output ---
Test3
one
two

echo Test4
echo one ^
& echo two
--- Output ---
Test4
one & echo two

要禁止转义下一个字符,可以使用重定向。

重定向必须在插入符号之前。
但是,在插入符号前存在一种对重定向的好奇心。

如果将标记放置在插入符号上,则标记将被删除。

echo Test5
echo one <nul ^
& echo two
--- Output ---
Test5
one
two

echo Test6
echo one <nul ThisTokenIsLost^
& echo two
--- Output ---
Test6
one
two

也可以将换行符嵌入到字符串中:

setlocal EnableDelayedExpansion
set text=This creates ^

a line feed
echo Test7: %text%
echo Test8: !text!
--- Output ---
Test7: This creates
Test8: This creates
a line feed

空行对于成功至关重要。这仅适用于延迟扩展,否则在换行后将忽略其余行。

之所以有效,是因为行尾的插入号会忽略下一个换行符并转义下一个字符,即使下一个字符也是换行符(在此阶段也总是忽略回车)。