使用批处理替换属性文件中的字段值

问题描述 投票:1回答:2

谁能帮我使用批处理替换属性文件中的字段值。

我在application.properties文件中有此字段:accessKey=AKIAJ2Q,我想将其替换为accessKey=XXXXX

我尝试使用sed命令作为建议的here,但是它不起作用。 Windows 10无法识别send命令。

我也尝试了以下代码:

SET key="XXXXX"
FOR /F %i IN (application.properties) DO SET accessKey=%key%
pause

任何帮助将不胜感激。

谢谢

batch-file command-line batch-processing
2个回答
0
投票

无法用纯批处理“替换”文本文件中的某些内容。您可以使用第三方工具,例如“查找替换”,甚至是某些PowerShell命令。但是您[[可以要做的是在替换您要查找的令牌的同时将文本文件“复制”到临时文件中。之后,您可以删除原始文件并将其替换为临时文件。这是代码:

@echo off setlocal enabledelayedexpansion set sourcefile=something.txt set tempfile=tempfile.txt set oldtoken=AKIAJ2Q set newtoken=XXXXX type nul>%tempfile% for /f "tokens=*" %%l in (%sourcefile%) do ( set line=%%l set line=!line:%oldtoken%=%newtoken%! echo !line!>>tempfile.txt ) del %sourcefile% move %tempfile% %sourcefile%

0
投票
肯定有一种方法可以使用纯批处理替换txt / properties文件中的字符串。

以上述示例替换application.properties中的accessKey文件。

@ECHO OFF SETLOCAL SET "sourcedir=C:\<Add directory path of application.properties>" ( FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\application.properties") DO ( FOR /f "tokens=1*delims==" %%g IN ("%%a") DO ( IF /i "%%g"=="accessKey" ( ECHO(%%g=xxxx ) ELSE ( ECHO(%%a) ) ) )>application_new.properties :: This new file now contains a modified version. rem ECHO(MOVE /y application_new.properties "%sourcedir%\application.properties" GOTO :EOF

© www.soinside.com 2019 - 2024. All rights reserved.