Windows 批处理的heredoc?
有没有一种方法可以以类似于 unix shell 中的heredoc 的方式批量指定多行字符串。 类似于:
cat <<EOF > out.txt
bla
bla
..
EOF
这个想法是从模板文件创建自定义文件。
Is there a way of specifying multiline strings in batch in a way similar to heredoc in unix shells. Something similar to:
cat <<EOF > out.txt
bla
bla
..
EOF
The idea is to create a customized file from a template file..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
OP想要的是非常具体的东西(创建带有输出的文本文件),并且接受的答案完美地做到了这一点,但是所提出的解决方案在特定上下文之外并不能很好地工作。 例如,如果我想将多行输入传递到命令中,则不能使用
( echo )
语法。 这就是对我有用的结果。给定一个名为“echolines.pl”的 Perl 脚本,其中包含以下内容(以模拟“真实”程序):
以及一个名为“testme.bat”的批处理文件,其中包含:
运行该脚本会产生预期的输出:
必须注意空格确保一切正常工作,任何地方都没有杂散空间。 具体来说:每个行尾应为脱字号 (^),后跟换行符,后续行必须立即以与号 (&) 开头,最后一行必须在要发送的最后一项之后立即开始管道。 如果不这样做将导致参数丢失或参数前后有额外的空格。
What the OP wanted was something very specific (creating a text file with the output) and the accepted answer does that perfectly, but the solution presented does not work well outside of that specific context. For example, if I want to pass multi-line input into a command, I can't use the
( echo )
syntax. Here's what wound up working for me.Given a perl script named "echolines.pl" consisting of the following (to simulate a 'real' program):
and a batch file named "testme.bat" containing:
running it produces the expected output:
Care with whitespace must be taken to ensure it all works correctly with no stray spaces anywhere. Specifically: each end-of-line should be a caret (^) followed by a newline, the subsequent lines must begin immediately with the ampersand (&) and the last line must have the pipe starting immediately after the last item to be sent. Failing to do this will result in missing parameters or extra whitespace before and after the parameters.
试试这个代码。 (底部的 JScript 代码将“out.html”写入磁盘)
Try this code. (JScript code at the bottom writes "out.html" to disk)
这更容易,并且非常类似于 cat << EOF> out.txt:
C:\>复制 con out.txt
这是我的第一行文字。
这是我的最后一行文字。
^Z
已复制 1 个文件。
输出如下所示:
C:\>type out.txt
这是我的第一行文字。
这是我的最后一行文本。
(复制 con + out.txt,键入您的输入,然后按 Ctrl-Z,然后复制文件)
COPY CON 表示“从控制台复制”(接受用户输入)
This is even easier, and closely resembles cat << EOF > out.txt:
C:\>copy con out.txt
This is my first line of text.
This is my last line of text.
^Z
1 file(s) copied.
Output looks like this:
C:\>type out.txt
This is my first line of text.
This is my last line of text.
(copy con + out.txt, type your input, followed by Ctrl-Z and file is copied)
COPY CON means "copy from the console" (accept user input)
此变体保存所有格式,
将其用作
输出
this variant saves all formatting
use it as
output will be
**它会在末尾添加一个空行,但您可以轻松解决这个问题,只需使用复制方法:
注意在每种情况下键入 ^C 和 ^Z 的位置。
**It will add an empty line at the end, but you can solve that easily, just by using the copy con method:
Beware where you type ^C and ^Z in each case.
据我所知还没有。
我知道的最接近的是
(
@
阻止命令 shell 本身打印它正在运行的命令,而echo.
允许您以空格开始一行。)Not as far as I know.
The closest I know of is
(
@
prevents the command shell itself from printing the commands it's running, andecho.
allows you to start a line with a space.)这是另一种方法。
输出示例:
Here's another approach.
Example output:
是的,很有可能。 ^ 是字面转义字符,只需将其放在换行符之前即可。 在此示例中,我还添加了额外的换行符,以便将其正确打印在文件中:
输出:
Yes, very possible. ^ is the literal escape character, just put it before your newline. In this example, I put the additional newline in as well so that it is properly printed in the file:
Output:
在 DosTips 上,siberia-man 发布了令人惊奇的行为演示错误的 GOTO 语句,格式为
(goto) 2>nul
。 随后,阿西尼和杰布记录了关于这种奇怪行为的一些额外有趣的发现。 它的行为基本上类似于EXIT /B
,只不过它允许 CALLed 例程中的串联命令在父调用者的上下文中执行。下面是一个简短的脚本,演示了大多数要点:
-- 输出 --
这种令人惊奇的行为使我能够编写一个优雅的批量模拟此处文档,其中包含许多可用于 UNIX 的选项。 我将 PrintHere.bat 作为独立实用程序实现,应将其放置在 PATH 中列出的文件夹中。 然后任何批处理脚本都可以轻松调用该实用程序来获取此处的文档功能。
以下是使用的一般语法:
这怎么可能实现?...我的 PrintHere 实用程序使用了
(GOTO) 2>nul
技巧两次。第一次使用
(GOTO) 2>nul
返回调用者,这样我就可以获得调用脚本的完整路径,以便 PrintHere 知道要读取哪个文件。 然后我第二次调用 PrintHere!第二次我使用
(GOTO) 2>nul
返回调用者并转到终止标签,以便不执行此处的文档文本。注意 - 下面的脚本在 tab 的定义中包含一个制表符 (0x09),位于
:start
标签的正下方。 某些浏览器可能难以显示和复制选项卡。 作为替代方案,您可以从我的保管箱下载 PrintHere.bat.txt ,然后将其重命名为 PrintHere.bat。我最初在 DosTips 上发布了PrintHere.bat,您可以在其中可以追踪未来的发展。
PrintHere.bat
完整的文档嵌入在脚本中。 下面是一些使用演示:
逐字输出
-- OUTPUT --
扩展变量(不需要启用延迟扩展)
--OUTPUT--
扩展变量并修剪前导空格
--OUTPUT--
输出可以重定向到文件
输出不能重定向为输入,但可以通过管道传输! 不幸的是,语法并不那么优雅,因为管道的两侧都在新的 CMD.EXE 进程中执行,因此
(GOTO) 2>nul
返回子 cmd 进程,而不是主脚本。Over at DosTips, siberia-man posted a demonstration of amazing behavior of an erroneous GOTO statement in the form of
(goto) 2>nul
. Aacini and jeb then documented some additional interesting discoveries about the odd behavior. It basically behaves like anEXIT /B
, except it allows concatenated commands within a CALLed routine to execute in the context of the parent caller.Here is a brief script that demonstrates most of the salient points:
-- OUTPUT --
This amazing behavior has enabled me to write an elegant batch emulation of a here doc with many of the options available to unix. I implemented PrintHere.bat as a stand-alone utility that should be placed in a folder listed within your PATH. Then any batch script can easily CALL the utility to get here doc functionality.
Here is the general syntax of usage:
How can this possibly be achieved?... My PrintHere utility uses the
(GOTO) 2>nul
trick twice.The first time I use
(GOTO) 2>nul
to return to the caller so I can get the full path to the calling script so that PrintHere knows what file to read from. I then CALL PrintHere a second time!The second time I use
(GOTO) 2>nul
to return to the caller and GOTO the terminating label so that the here doc text is not executed.Note - the script below contains a tab character (0x09) in the definition of tab, directly below the
:start
label. Some browsers may have difficulty displaying and copying the tab. As an alternative, you can download PrintHere.bat.txt from my dropbox, and simply rename it to PrintHere.bat.I originally posted PrintHere.bat at DosTips, where you can track future development.
PrintHere.bat
Full documentation is embedded within the script. Below are some demonstrations of usage:
Verbatim output
-- OUTPUT --
Expand variables (delayed expansion need not be enabled)
--OUTPUT--
Expand variables and trim leading spaces
--OUTPUT--
Output can be redirected to a file
The output cannot be redirected as input, but it can be piped! Unfortunately, the syntax is not nearly as elegant because both sides of a pipe are executed in a new CMD.EXE process, so
(GOTO) 2>nul
returns to a child cmd process, and not the master script.带参数的宏的用法 允许以更简单的方式编写“heredoc”:
The usage of a macro with parameters allows to write a "heredoc" in a simpler way:
@jeb
另一个变体:
@jeb
another variant:
参考rojo的帖子 https://stackoverflow.com/a/15032476/3627676
当然,他的解决方案就是我的解决方案寻求一些时间(当然,我可以尝试实现类似的东西,但懒惰会推动进步:))。 我想补充的一件事是对原始代码的微小改进。 我认为如果将重定向到文件写在行尾会更好。 在这种情况下,heredoc 起始线可以更严格,其分析也更简单。
我通过这段代码建议什么? 让我们考虑一下。
Rojo 的代码非常严格:
call
和:heredoc
之间的字符串中不允许有多个空白字符call :heredoc
粘在行的边缘(行的开头不允许有任何空格)我建议的事情:
更新 1:
对 Heredoc 开头的检查和执行的改进:
call :heredoc LABEL
或call :heredoc :LABEL
。 因此,在打印heredoc内容后,可以跳转到另一个标签、脚本末尾或运行exit /b
。更新 2:
for
的分隔符为(
)
> ;
&
|
TAB
,
;
=
SPACE
/I
添加到if
更新 3:
通过以下链接您可以找到独立脚本的完整版本(可以嵌入到您的脚本中) https://github.com/ildar-shaimordanov/cmd.scripts/blob/master/heredoc.bat
Referring to rojo's post at https://stackoverflow.com/a/15032476/3627676
Definitely, his solution is what I am seeking for few time (of course, I could try to implement something similar to this but laziness moves progress :)). One thing I'd like to add is a minor improvement to the original code. I thought it would be better if redirection to file was written at the end of the line. In this case the heredoc starter line could be stricter and its analysis simpler.
What am I suggesting by this code? Let's consider.
Rojo's code is very strict:
call
and:heredoc
call :heredoc
is sticky to the edge of the line (no any whitespaces allowed at the beginning of the line)Things I am suggesting:
Update 1:
Improvements to checking and performing of the heredoc beginning:
call :heredoc LABEL
orcall :heredoc :LABEL
. So after printing the heredoc content it is possible to jump to another label, end of script or runexit /b
.Update 2:
for
are(
)
>
&
|
TAB
,
;
=
SPACE
/I
added toif
Update 3:
By the following link you can find the full version of the standalone script (embedding in your scripts is available) https://github.com/ildar-shaimordanov/cmd.scripts/blob/master/heredoc.bat
您可以使用 FOR /F 循环创建带引号的文本块,因此不需要转义特殊字符,例如
<>|&
只有%
具有被逃脱。这有时很有用,比如创建 html 输出。
输出
我尝试解释代码。
LF 变量包含一个换行符,NL 变量包含
^^
。这可以与百分比扩展一起使用,在行尾放置一个换行符和一个插入符号。
通常,FOR /F 将引用的文本拆分为多个标记,但仅一次。
当我插入换行符时,FOR 循环也会分成多行。
第一行和最后一行的引号只是为了创建 FOR 循环的正确语法。
任何行的前面都是
_
,因为第一个字符将从前一行的多行插入符中转义,如果引号是第一个字符,它将失去转义功能。使用
_
分隔符,因为空格或逗号会导致 XP 出现问题(否则 XP-Bug 虚假会尝试访问垃圾文件名)。行尾的插入符号也仅针对 XP-Bug。
当带引号的文本包含不带引号的
,;=
字符时,XP-Bug 就会生效You can create a quoted block of text with a FOR /F loop, so you didn't need to escape special characters like
<>|&
only%
have to be escaped.This is sometimes usefull like creating a html output.
Output
I try to explain the code.
The LF variable contains one newline character, the NL variable contains
^<LF><LF>^
.This can be used with the percent expansion to place ONE newline character and one caret at the line end.
Normally a FOR /F split a quoted text into multiple tokens, but only once.
As I insert newline characters the FOR-loop also splits into multiple lines.
The quote at the first and at the last line are only to create the correct syntax for the FOR-loop.
At the front of any line are
_
as the first character will be escaped from the multi line caret of the previous line, and if the quote is the first character it looses the escape capability.The
_
delims is used, as spaces or commas causes problems with XP (Else the XP-Bug spurious tries to access garbage filenames).The caret at the line end is also only against the XP-Bug.
The XP-Bug comes in effect when a quoted text contains unquoted
,;=<space>
characters这是 ephemient 优秀解决方案的一个变体。 这允许您将多行通过管道传输到另一个程序中,而无需实际创建文本文件并将输入重定向到您的程序:
对于一个快速、有效的示例,您可以将
yourprog.exe
替换为more< /代码>:
输出:
Here's a variant of ephemient's excellent solution. This allows you to pipe multiple lines into another program without actually creating a text file and input redirecting it to your program:
For a quick, working example, you can replace
yourprog.exe
withmore
:Output:
扩展 ehemient 帖子,我认为这是最好的,以下将执行一个管道:
在 ehemient 的帖子中,他在开头重定向,这是一个很好的风格,但您也可以在末尾重定向:
请注意“@echo ”。 永远不会包含在输出和“@echo”中。 其本身给出一个空行。
Expanding on ephemient post, which I feel is the best, the following will do a pipe:
In ephemient's post he redirected at the beginning, which is a nice style, but you can also redirect at the end as such:
Note that "@echo." is never included in the output and "@echo." by itself gives a blank line.
在紧要关头,我使用以下方法(这不会削弱任何其他方法,这只是个人喜好):
我使用 for 循环遍历一组字符串:
这是我当前正在处理的脚本中的另一个实际示例:
In a pinch, I use the following method (which doesn't diminish any other methods, this is just a personal preference):
I use a for loop through a set of strings:
Here is another practical example from the script I'm currently working on:
在 .bat 文件中:
然后
会产生
一点混乱,必须将
@echo.
放在每行的开头,但它基本上可以满足您的要求:将依赖文件滚动到脚本中的能力文件本身。还有很多其他解决方案,但所有这些都需要添加更多代码才能以更简洁的方式完成基本相同的事情。 在一种情况下,甚至需要整个其他 .bat 文件作为新的依赖项!
感谢 B.Reynolds,我的回答受到了他们的启发。
In a .bat file:
then
produces
A bit messier, having to put
@echo.
at the beginning of each line, but it does basically what you want: The ability to roll a dependancy file into the script file itself.There are a lot of other solutions, but all of those require adding a bunch more code to do basically the same thing in a neater way. In one case, even requiring a whole other .bat file as a new dependancy!
Props to B.Reynolds, my answer was inspired by theirs.
在 Microsoft NMake makefile 中,可以按照线程所有者的要求使用真正的UNIX heredocs。 例如,这是创建文件 Deploy.sed 的显式规则:
其中 << 扩展为 NMake 在执行规则时动态创建的临时文件名。 也就是说,当 Deploy.sed 不存在时。 好处是 NMake 变量也被扩展了(这里是变量 NAME 和 VERSION)。 将其保存为makefile。 在 makefile 目录中打开 DOS 框并使用:
创建文件,然后使用:
删除它。 NMake 是所有版本的 Visual Studio C++ 的一部分,包括 Express 版本。
In a Microsoft NMake makefile one can use true UNIX heredocs, as the thread owner requested them. For example, this is an explicit rule to create a file Deploy.sed:
where << expands into a temporary filename NMake creates on the fly when executing the rule. That is, when Deploy.sed does not exist. The nice thing is that NMake variables are expanded too (here the variables NAME and VERSION). Save this as makefile. Open a DOS-box in the directory of makefile and use:
to create the file, and:
to remove it. NMake is part of all versions of Visual Studio C++, including the Express-editions.