Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

How to split double quoted line into multiple lines in Windows batch file?

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"

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I see three possible workarounds.

1) Building the line combining multiple for-parameters.

@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) Leaving the "quote" at the end of each line

@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 Added: 3) Disappearing quotes

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"

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...