batch file to search and replace a string

后端 未结 3 1711
不知归路
不知归路 2021-01-22 19:38

I need a batch file that should search the PC for all files issued today named as \"example.ini\" and replaces a string which will be in the second line of \"example.ini\", it s

3条回答
  •  情深已故
    2021-01-22 20:31

    Change String1 by String2 in the second line of files named example.ini that has been created today in any subdirectory of drive c:

    @echo off
        setlocal enableextensions enabledelayedexpansion
    
        rem Arguments:
        rem     %1 = search string
        rem     %2 = replace string
        rem     [ %3 = file in where to replace ] 
        rem            this parameters is internally used by the 
        rem            batch file while processing
    
        rem chech for parameters
        if "%~2"=="" goto :EOF
    
        rem retrieve parameters
        set "_search=%~1"
        set "_replace=%~2"
    
        rem check if asked to replace in a file 
        rem this will be done recursively from this same batch
        if not "%~3"=="" (
            set "_file=%~3"
            goto doFileReplace
        )
    
        forfiles /P C:\ /S /M example.ini /D +0 /C "cmd /c if @isdir==FALSE findstr /c:\"%_search%\" \"@path\" >nul && %~dpnx0 \"%_search%\" \"%_replace%\" @path "
    
        goto :EOF
    
    :doFileReplace
        echo "%_file%"
        set "_tempFile=%temp%\%~nx0.tmp"
        break > "%_tempFile%"
        (for /F "tokens=1,* delims=:" %%l in ('findstr /n /r "." "%_file%"') do (
            if %%l EQU  2 (
                set "_text=%%m"
                echo !_text:%_search%=%_replace%!
            ) else (
                echo %%m
            )
        ))>>"%_tempFile%"
    
        copy /Y "%_tempFile%" "%_file%" >nul 
        goto :EOF
    

提交回复
热议问题