如何在Windows批处理文件中嵌入文本文件 [英] How to embed a text file in a Windows batch file
问题描述
我需要创建一个写入文本文件(可能包括变量)的批处理文件.在带有bash的Unix中,这很简单:
I need to create a batch file that writes a text file (possibly including variables). In Unix with bash this is trivial:
#!/bin/bash
ver="1.2.3"
cat > file.txt <<EOL
line 1, ${ver}
line 2
line 3
...
EOL
使用批处理文件最简单的方法是什么?
What is the simplest way to do this with a batch file?
注意:在Windows批处理中,使用 heredoc的"heredoc"例程是否有完整的解决方案?
,但对于临时使用而言似乎太复杂了.我正在寻找一种快速简单的方法.Note: there is a complete solution using an 'heredoc' routine at heredoc for Windows batch? but it seems too complex for ad-hoc use. I'm looking for a quick and simple way.
推荐答案
如果只有一个数据块(文本),则跟踪效果很好
The follwoing works fine, if there is just one block of data (text)
@ECHO OFF
set string=beautyful
REM get linenumber for Data:
for /f "tokens=1 delims=:" %%a in ('findstr /n /b "REM StartData" "%~f0"') do set ln=%%a
REM print Data (use call to parse the line and evaluate variables):
(for /f "usebackq skip=%ln% delims=" %%a in ("%~f0") do call echo %%a)>"new.txt"
type "new.txt"
goto :eof
REM StartData
hello %string% world
line 2
line 3
如果数据中没有变量,请省略call
.优势:无需逃脱任何东西.即使通常是有毒字符也可以工作(代替for
循环,也可以只使用more +%ln% "%~f0"
).可悲的是,当您使用call
解析行以获取变量时,您失去了这一优势.
If you don't have variables in the data, omit the call
. Advantage: no need to escape anything. Even usually poisonous characters work (instead of the for
loop, you can also just use more +%ln% "%~f0"
). Sadly, you loose this advantage, when you use call
to parse the lines for variables.
这篇关于如何在Windows批处理文件中嵌入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!