1

Can anyone help me to replace a field value in property file using batch.

I have this field in my application.properties file: accessKey=AKIAJ2Q and I want to replace it with accessKey=XXXXX

I tried with sed command as recommanded here but it didn't work. The send command is not recognized by windows 10.

I tried also the following code:

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

Any help would be appreciated.

Thanks

Community
  • 1
  • 1
Anis D
  • 761
  • 11
  • 25
  • Possible duplicate of [How can you find and replace text in a file using the Windows command-line environment?](http://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir) – Hexaholic Dec 16 '15 at 11:00

2 Answers2

1

There is surely a way to replace a string inside a txt/properties file using pure batch.

Taking above example to replace accessKey in application.properties file.

@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
Vaibhav Jain
  • 1,939
  • 26
  • 36
0

There is no way to "replace" something inside a text file with pure batch. You could use a 3rd party tool like Find'n'Replace or even some PowerShell commands. But what you can do is to "copy" the text file into a temp file while replacing the token you are looking for. Afterwards you can delete the original file and replace it with the temporary one. Here is the code:

@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%
MichaelS
  • 5,941
  • 6
  • 31
  • 46
  • Thank you @MichaelS for your answer. I did it with PowerShell command: type application.properties| powershell -Command "$input | ForEach-Object { $_ -replace \"AKIAJ2Q \", \"XXXXX\" }" > application1.properties – Anis D Dec 17 '15 at 10:02