我有一个模板文件(比方说myTemplate.txt),我需要做一些编辑以便从这个模板创建我自己的文件(比方说myFile.txt)。
因此,该模板包含如下代码行
env.name=
env.prop=
product.images.dir=/opt/web-content/product-images现在,我希望将其替换为:
env.name=abc
env.prop=xyz
product.images.dir=D:/opt/web-content/product-images因此,我正在寻找批处理命令来执行以下操作;
1. Open the template file.
2. Do a kind of find/replace for the string/text
3. Save the updates as a new file我该如何实现这一点?
发布于 2012-02-13 20:11:18
最简单的方法是修改您的模板,使其如下所示:
env.name=!env.name!
env.prop=!env.prop!
product.images.dir=/opt/web-content/product-images然后在启用延迟扩展的情况下使用FOR循环读写文件:
@echo off
setlocal enableDelayedExpansion
set "env.name=abc"
set "env.prop=xyz"
(
for /f "usebackq delims=" %%A in ("template.txt") do echo %%A
) >"myFile.txt"注意,在整个循环中使用一个覆盖重定向>要比在循环中使用附加重定向>>快得多。
上面假设模板中没有以;开头的行。如果是这样,那么您需要将FOR EOL选项更改为永远不会开始一行的字符。也许等于- for /f "usebackq eol== delims="
此外,上面还假设模板不包含您需要保留的任何空行。如果有,您可以按如下方式修改以上内容(这也消除了任何潜在的EOL问题)
@echo off
setlocal enableDelayedExpansion
set "env.name=abc"
set "env.prop=xyz"
(
for /f "delims=" %%A in ('findstr /n "^" "template.txt"') do (
set "ln=%%A"
echo(!ln:*:=!
)
) >"myFile.txt"还有最后一个可能会使isse复杂化的问题--如果模板包含!和^文本,则可能会出现问题。您可以对模板中的字符进行转义,也可以使用一些额外的替换。
template.txt
Exclamation must be escaped^!
Caret ^^ must be escaped if line also contains exclamation^^^!
Caret ^ should not be escaped if line does not contain exclamation point.
Caret !C! and exclamation !X! could also be preserved using additional substitution.templateProcessor.bat中的摘录
setlocal enableDelayedExpansion
...
set "X=^!"
set "C=^"
...https://stackoverflow.com/questions/9257193
复制相似问题