2

I want to be able to replace a line in a properties file but i only know part of the line string at any one time

Heres the line i want to replace: mb.datasource.password=ENC(8dF45fdD)

with this: mb.datasource.password=apassword

What i have just now is this

@echo off &setlocal
set "search=mb.datasource.password="
set "replace=mb.datasource.password=apassword"
set "textfile=mb.properties"
set "newfile=mb-new.properties"
(for /f "delims=" %%i in (%textfile%) do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>"%newfile%"

This ends up giving me mb.datasource.password=apassword=ENC(8fFdeUdK)

I can't just find the full string it needs to only be mb.datasource.password= because the part after the equals changes

Any help would be greatly appreciated?

3
  • 1
    i think the only way it would be to use regex, and i don't know if you can do that in ordinary batch files. i have recently worked with CScript, look it up, it can run scripts written in different languages (like js or typescript) as a batch Commented Feb 5, 2016 at 13:31
  • Ahh okay, i gave up with the batch and just wrote a quick c# console app to do it instead, thanks anyway for your help Commented Feb 5, 2016 at 13:36
  • Possible duplicate of Find until that line and replace with another text file windows batch script Commented Feb 5, 2016 at 13:48

1 Answer 1

1

You can do it with batch. I put together a quick script and it worked for me:

@ECHO OFF
SETLOCAL EnableExtensions

SET SourceFile="mb.properties"
SET OutputFile="mb-new.properties"
SET "FindKey=mb.datasource.password"
SET "NewValue=apassword"

REM Basic parse for INI file format.
(FOR /F "usebackq eol= tokens=1,* delims==" %%A IN (`TYPE %SourceFile%`) DO (

    REM If the key value matches, build the line with the new value.
    REM Otherwise write out the existing value.
    IF /I "%%A"=="%FindKey%" (
        ECHO %%A=%NewValue%
    ) ELSE (
        ECHO %%A=%%B
    )

)) > %OutputFile%

REM Replace old with new.
DEL %SourceFile%
MOVE %OutputFile% %SourceFile%

ENDLOCAL

A few notes about the above:

  • I assumed basic INI file format.
  • The FOR loop will skip blank lines so they would be removed from the new output file. There are ways around this using tricks with the FIND command if the blanks are needed.
  • If you have special chars (% or ! especially) - this may cause some problems, but if you have just "normal" text then it should be fine.
Sign up to request clarification or add additional context in comments.

1 Comment

The file is massive so spaces need to be kept for organisation, i also can't guarantee that special characters won't be used

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.