Search code examples
windowsbatch-filecmd

search for string recursively and replace the string


I need to find a specific string in the Windows PATH recursively and replace the string with another string:

Task # 1

I identified(with help) on how to identify the path of available string using the below script.

findstr /s /i /m /c:"topaz3258" H:\MKS\build\host\dev\*.* > H:\topaz3258\result.txt

Task # 2

Now I need your assistance to update "topaz3258" with "topaz103258" in all the above path identified for the string. The file type is ".ini" and ".cmd" files.

Note: Powershell is restricted in the organization, so I have to use Batch script.


Solution

  • With powershell scripts you can do a regex replacement within a file pretty easy. I just pulled an example from something I had already, this should probably work in general. but this is just to do one file

    (gc "input filename" -raw) -replace 'topaz3258', 'topaz103258' | Out-File -encoding ASCII "output filename"

    You can iterate over files pretty easily though https://theitbros.com/powershell-script-for-loop-through-files-and-folders/

    edit, im just writing this freehand but it might look something like

    $files = Get-ChildItem H:\MKS\build\host\dev\ -Recurse *.*
    
    foreach ($f in $files){
    
    (gc $f.FullName -raw) -replace 'topaz3258', 'topaz103258' | Out-File -encoding ASCII $f.FullName
    
    }
    

    if you dont want to do it in-place you can specify a different output path or else just copy the folder tree before operating on it. Depends on what you need exactly. star dot star is a very wide net to cast btw, you might want to filter by text files only or something


    If you dont have powershell

    I quickly put this together from other answers (Also edited). It will no longer make a new file, it writes directly into the original file. This is dangerous, you cant go back. There is no undo so make a temporary backup somehow. The script will preserve blank lines. It will not respect word boundaries so for example

    red blue reddit (red -> green) green blue greendit

    @echo off
    SET FIND_STR=topaz3258
    SET REPL_STR=topaz103258
    SET ROOT_DIR=H:\MKS\build\host\dev\
    
    
    for /R "%ROOT_DIR%" %%a in (*.txt) do (
        :: say the filename
        echo %%a
    
        for /f "delims=" %%i in ('type "%%a" ^| find /v /n "" ^& break ^> "%%a"') do (
            set "line=%%i"
            setlocal enabledelayedexpansion
            set "line=!line:*]=!"
            if defined line set "line=!line:%FIND_STR%=%REPL_STR%!"
            >>"%%a" echo(!line!
            endlocal
        )
    )