替换字符串的蝙蝠脚本创建空文件 [英] bat script for replacing strings creates empty file
问题描述
我正在使用此bat文件将web.config中的值从httpTransport修改为httpsTransport。如果我将输出定向到另一个文件,它将很好地工作。如果我尝试覆盖我的文件,则会创建一个空文件。
I'm using this bat file to modify a value in a web.config from httpTransport to httpsTransport. It works well if I direct my output to another file. If I try to overwrite my file it creates an empty file.
@echo off &setlocal
set "search=httpsTransport"
set "replace=http123Transport"
set INTEXTFILE=D:\teste_bat\Web.config
set OUTTEXTFILE=D:\teste_bat\WebTemp.config
(for /f "delims=" %%i in ('findstr "^" "%INTEXTFILE%"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>>"%OUTTEXTFILE%"
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%
任何帮助都会被取消
推荐答案
以下代码在两种情况下均失败 INTEXTFILE
和 OUTTEXTFILE
指向同一文件,因为输出重定向>
在开始时准备输出文件,因此会创建一个空文件,然后由 findstr
读取该文件:
The following code fails in case both INTEXTFILE
and OUTTEXTFILE
point to the same file, because the output redirection >
prepares the output file at the beginning, so it creates an empty file, which is then read by findstr
:
set "INTEXTFILE=D:\teste_bat\Web.config"
set "OUTTEXTFILE=D:\teste_bat\Web.config"
> "%OUTTEXTFILE%" (
for /f "delims=" %%i in ('findstr "^" "%INTEXTFILE%"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
)
)
用替换
也不起作用,因为这会将新数据追加到原始文件中。>
>>
Replacing >
by >>
does also not work, because this appends the new data to the original file.
要克服这个问题,您有两种选择:
To overcome this, you have got two options:
-
要写入其他文件并替换原始文件末尾添加新的
To write to a different file and to replace the original file by the new one at the end:
set "INTEXTFILE=D:\teste_bat\Web.config"
set "OUTTEXTFILE=D:\teste_bat\WebTemp.config"
> "%OUTTEXTFILE%" (
for /f "delims=" %%i in ('findstr "^" "%INTEXTFILE%"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
)
)
move /Y "%OUTTEXTFILE%" "%INTEXTFILE%"
由于性能更好,因此建议使用此变体。
This is the recommended variant due to better performance.
为确保在读取文件之前,请先读取文件应用输出重定向:
To ensure that the file is read before the output redirection is applied:
set "INTEXTFILE=D:\teste_bat\Web.config"
set "OUTTEXTFILE=D:\teste_bat\Web.config"
for /f "delims=" %%i in ('findstr "^" "%INTEXTFILE%" ^& ^> "%OUTTEXTFILE%" rem/') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
>> "%OUTTEXTFILE%" echo(!line!
endlocal
)
由于存在多个文件访问操作(由于>
),但可以避免使用临时文件。>部分%OUTTEXTFILE% rem /
将耗尽 之后被 findstr
读取的文件,然后将其附加到循环主体的后面。
This is worse in performance since there are multiple file access operations (appending to the file per each loop iteration due to >>
), but it prevents the need of a temporary file. The portion > "%OUTTEXTFILE%" rem/
depletes the file after being read by findstr
, then it is appended to later in the loop body.
这篇关于替换字符串的蝙蝠脚本创建空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!