这可能已经在互联网上得到了答案,但我找不到解决方案。
我有一个.ini文件,其中包含很多文本,这里有一个例子:
[General]
FullScreen = True
InternalResolution = 0
我需要设置一个批处理文件,该文件搜索这一行InternalResolution并更改不同数字的值,例如5。输出应该是这样的:
[General]
FullScreen = True
InternalResolution = 5
我有两个问题,第一个问题是值=0有时可能是=1或=2,而且所有的空格都必须存在于文件中(应用程序依赖于这个ini文件,所以我无法删除空格。我试过这个:
@echo off
setlocal disableDelayedExpansion
:Variables
set InputFile=myfile.ini
set OutputFile=myfiletemp.ini
set "_strFind=InternalResolution = 0"
set "_strInsert=InternalResolution = 5"
:Replace
>"%OutputFile%" (
for /f "usebackq delims=" %%A in ("%InputFile%") do (
if "%%A" equ "%_strFind%" (echo %_strInsert%) else (echo %%A)
)
)
DEL %InputFile%
MOVE %OutputFile% %InputFile%
ENDLOCAL
只有当InternalResolution值为0时,它才有效。如果值不同于0,我不知道如何替换该行。应该有一种方法来搜索该行是否包含文本InternalResolution=X,并替换整行或值。
谢谢。
FIND
是一个不错的选择。一种更简单的方法是将其分离为两个令牌%%A
%%B
,然后只测试%%A
是否等于%_strFind%
(我也更改了它(。
@echo off
:Variables
set InputFile=myfile.ini
set OutputFile=myfiletemp.ini
set "_strFind=InternalResolution"
set "_strInsert=InternalResolution = 5"
:Replace
>%OutputFile% (
for /f "usebackq tokens=1* delims= " %%A in ("%InputFile%") do (
if "%%A" equ "%_strFind%" (echo %_strInsert%) else (echo %%A %%B)
)
)
MOVE /Y %OutputFile% %InputFile%
在Windows 10笔记本电脑上测试
注意:可能无法处理有毒字符
您可以使用子字符串替换,如下所示:
:Replace
> "%OutputFile%" (
for /F "usebackq delims=" %%A in ("%InputFile%") do (
set "line=%%A"
setlocal EnableDelayedExpansion
if "!line!" equ "%_strFind%!line:*%_strFind%=!" (
echo(!_strInsert!
) else (
echo(%%A
)
endlocal
)
)
Windows 10 64位。PowerShell 5.1
使用get content和正则表达式将文本替换为PowerShell 5.1。
等号前后必须正好有一个空格。
InternalResolution = 0-9
替换为InternalResolution = 5
(Get-Content "myfile.ini") -replace "InternalResolution = d", "InternalResolution = 5" | Set-Content "myfiletemp.ini"
了解如何用powershell替换文本、获取内容、-replacement和regex
Regex
Windows 10 64位
用cmd的FOR和IF命令查找并替换文本
替换:
InternalResolution = 0
InternalResolution = 1
InternalResolution = 2
InternalResolution = abc
带有:
InternalResolution = whatever value you want
InternalResolution= whatever
不被替换。
@echo off
setlocal enableextensions
set InputFile=myfile.ini
set FindStr=InternalResolution
copy /y %InputFile% %InputFile%.bak
(for /f "usebackq tokens=1*" %%g in ("%InputFile%") do if "%%g" equ "%FindStr%" (echo %%g = 5) else (echo %%g %%h))> %temp%#
MOVE /Y %temp%# %InputFile%