如何在 Windows 批处理文件中将双引号行拆分为多行? [英] How to split double quoted line into multiple lines in Windows batch file?

查看:36
本文介绍了如何在 Windows 批处理文件中将双引号行拆分为多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows 批处理文件中的长命令可以使用 ^ 拆分为多行,如长命令中所述在 Windows Vista 批处理 (.bat) 文件中拆分为多行.

Long commands in Windows batch files can be split to multiple lines by using the ^ as mentioned in Long commands split over multiple lines in Windows Vista batch (.bat) file.

但是,如果插入符号位于双引号字符串中,则它不起作用.例如:

However, if the caret is inside a double quoted string, it won't work. For example:

echo "A very long line I want to ^
split into two lines"

这将打印 我想要 ^ 的很长的一行并告诉我 split 是一个未知命令.

This will print "A very long line I want to ^ and tell me split is an unknown command.

有没有办法解决这个问题?

Is there a way to get around this?

推荐答案

我看到了三种可能的解决方法.

I see three possible workarounds.

1) 构建组合多个 for 参数的行.

@echo off
SETLOCAL EnableDelayedExpansion

set "line="
for %%a in ("line1" 
"line2"
"line3"
"line4"
) do set line=!line!%%~a
echo !line!

缺点:当文本中有 ?* 时,它会掉线.

Drawback: It drops lines, when there is a ? or * in the text.

2) 在每行末尾留下引用"

@echo on
SETLOCAL EnableDelayedExpansion

set "line=line1 & x#"^
 "line2 & a#"^
 "line3 & b #"^
 "line4 & c "

set "line=!line:#" "=!"
echo !line!

每行的第一个空格很重要,因为插入符号可以用作多行字符,但它也会转义第一个字符,因此引号也会被转义.
所以我在建好这条线后替换掉了不必要的#" ".

The first space in each line is important, because the caret works as multiline character but it also escapes the first character, so also a quote would be escaped.
So I replace the unnessary #" " after building the line.

EDIT 添加:3) 消失的引号

setlocal EnableDelayedExpansion
echo "A very long line I want to !="!^
split into two lines"

在我看来,这是最好的方式,它在解析器首先看到引号时起作用,因此最后一个脱字符将起作用,因为它似乎在引号之外.
但是这个 !="! 表达式会扩展名为 =" 的变量,但是这样的变量名不能存在(等号不能作为第一个字符出现)所以它扩展为空.

In my opinion this is the best way, it works as the parser first see the quotes and therefore the last caret will work, as it seems to be outside of the quotes.
But this !="! expression will expand the variable named =", but such a variable name can't exists (an equal sign can't occur as first character) so it expands to nothing.

您还可以创建安全表达式,它们总是从引号中转义出来,与行中是否有引号无关.
!="^"!

You can also create safe expressions, they will always escape out of quotes, independent if there is a quote or not in the line.
!="^"!

echo This multiline works !="^"!^
as expected
echo "This multiline works !="^"!^
too"

如果你想避免延迟扩展,你也可以使用 -FOR-Loop 之类的

If you want avoid delayed expansion, you could also use a -FOR-Loop like

for %%^" in ("") do (
echo "This multiline works %%~"^
too"
)

这篇关于如何在 Windows 批处理文件中将双引号行拆分为多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆