@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 ECHO
ed 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.