How to replace a word in every CFG file of a folder with the CFG file name?

I would like to know if there is a possibility with batch or script to change a word being always the same word in several *.cfg files by replacing it with the name of the CFG file?

For example in these *.cfg files


I have always the word kof98 on line 4 in each CFG file. I would like to replace the word kof98 by aaaaaa without extension like the file name for the first CFG file. And make the same for the second CFG file by replacing kof98 with bbbbbb, etc.

1 answer

  • answered 2018-01-14 10:28 Mofi

    This is an easy to achieve task with using JREPL.BAT written by Dave Benham which is a batch file / JScript hybrid to run a Perl regular expression on a file using JScript.

    @echo off
    if not exist "*.cfg" goto :EOF
    if not exist "%~dp0jrepl.bat" goto :EOF
    for %%I in (*.cfg) do call "%~dp0jrepl.bat" "kof98" "%%~nI" /F "%%I" /O -
    rem JREPL.BAT v7.9 leaves behind JREPL\XBYTES.HEX in folder for temporary files.
    rd /Q /S "%TEMP%\JREPL" 2>nul

    The batch file first checks if there is any *.cfg file in current directory and immediately exits if this condition is not true, see Where does GOTO :EOF return to?

    The batch file JREPL.BAT must be stored in same directory as the batch file with the code above. For that reason the batch file checks next if JREPL.BAT really exists in directory of the batch file and exits if this condition is not true.

    The command FOR searches in current directory for non hidden files matching the wildcard pattern *.cfg and calls for each found CFG file the batch file JREPL.BAT to case-sensitive replace any occurrence of kof98 by the name of the CFG file without file extension.

    For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

    • call /? ... explains also %~dp0 ... drive and path of argument 0 being the batch file itself.
    • echo /?
    • for /?
    • goto /?
    • if /?
    • jrepl.bat /?
    • rd /?
    • rem /?