批处理命令:在文件内查找/替换文本

3

我有一个模板文件(假设为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

我该如何实现这个?
1个回答

6
最简单的方法是修改您的模板,使其类似于这样:
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"

最后一个可能会引起麻烦的问题是,如果模板包含!^这些字符,你可能会遇到问题。你可以在模板中转义这些字符,或者使用一些额外的替换。

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=^"
...

1
太好了!谢谢。我不得不进行一些微小的调整,以使其能够从可调用的批处理文件中工作,这就是将"set ln=%%A"更改为set "ln=%%A"(注意第一个双引号的位置)。此外,为了使用名为template_file的变量,我用^"^"^"%%template_file%%^"^"^"替换了template.txt - mwag
@mwag - 谢谢。我很惊讶在你之前没有人发现这些错别字 - 这个答案已经有8年了!我编辑了我的回答并将引用移到了它应该在的位置。我还更正了FOR /F命令中错误的反引号为正确的单引号。您对模板文件的参数化过于复杂 - 没有必要使用延迟扩展或转义引号。您可以简单地使用"%template_file%"。或者如果您想将模板指定为第一个批处理参数,则使用"%~1" - dbenham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接