2012-02-13 107 views
2

我有一個模板文件(說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 

我該如何做到這一點?

回答

5

,最快的途徑是修改你的模板是這個樣子:

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