1

I have a properties file (server.properties) and it looks like this:

ipaddress=10.x.x.x
serverName=someName

and a lot of other values.

Let's say it is located at C:\Server\server.properties
Is there a way to modify the values using a batch script.

What would I do if I want to change serverName from "someName" to "myName" ? I can't use line numbers because it can change anytime.

This is not a duplicate of How can you find and replace text in a file using the Windows command-line environment?

I am trying to figure out how to replace the value of a property. Not replacing one word with another.

Thanks.

Community
  • 1
  • 1
ecthelion84
  • 356
  • 2
  • 5
  • 14
  • 1
    This is not a duplicate of http://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir – ecthelion84 Sep 29 '14 at 17:41

1 Answers1

2
@ECHO OFF
SETLOCAL
SET "sourcedir=C:\106x"
(
 FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\q25967146.txt") DO (
  FOR /f "tokens=1*delims==" %%g IN ("%%a") DO (
   IF /i "%%g"=="servername" (ECHO(%%g=%~1
    ) ELSE (ECHO(%%a)
  )
 )
)>newfile.txt
:: newfile.txt now contains a modified version.
:: This line will overwrite the original

ECHO(MOVE /y newfile.txt "%sourcedir%\q25967146.txt"

GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

I used a file named q25967146.txt containing your data for my testing. Change the name to suit yourself.

Produces newfile.txt

The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)

The method shown above deliberately creates a new file in order that the new version can be viewed without damaging the original.

Note that this version will remove any empty lines from the file when creating the new version. This can be overcome if required.

To run this routine, use

thisbatchname "replacement text"

If the replacement text is a single string without spaces or other separators (as seems likely) then the quotes can be omitted.


Code fixed - there was a delims==" in the for /f...%%a... line, this should be delims= (one =.) The double = is correct in the for /f ... %%g... line.

To replace the file, activate the move as instructed by replacing ECHO(MOVE with MOVE - once you've verified that the procedure is operating correctly. As you've seen, one small error and damage could have been done - saved by the two-step operation.

Magoo
  • 77,302
  • 8
  • 62
  • 84