locked
Batch script for finding files and replacing a text string in them - not working correctly RRS feed

  • General discussion

  • Hi All,

    I need some help about the following cmd script which is supposed to do the following task on Windows 7 SP1 machines:

    Searching for certain configuration files and replace a text string in it. So I am searching for the files with dir and putting them into a temp.tmp. After that I am reading it through loop and trying to make the change.

    dir /s /a /b "c:\path\*.ini" > %userprofile%\temp.tmp

    for /F "tokens=* delims=," %%G IN (%userprofile%\temp.tmp) DO (
        setlocal enableextensions disabledelayedexpansion

        set "config="%%G""
        set "Value_to_change=Y"
       
        for /f "tokens=*" %%l in ('type "%config%"^&cd.^>"%config%"'
        ) do for /f "tokens=1 delims== " %%a in ("%%~l"
        ) do if /i "%%~a"=="Param_to_change" (
            >>"%config%" echo(Param_to_change=%Value_to_change%
        ) else (
            >>"%config%" echo(%%l
        )

        type "%config%"

        endlocal

    )

    But does not work as expected. The result is

    The system cannot find the path specified.
    The system cannot find the path specified.

    If I put the path to ini file, i.e bypassing the search and loop - I works. 

    @echo off
    set path_to_file="C:\path_to_file\file.ini"

        setlocal enableextensions disabledelayedexpansion

        set "config="%path_to_file%""
        set "Value_to_change=Y"

        for /f "tokens=*" %%l in ('type "%config%"^&cd.^>"%config%"'
        ) do for /f "tokens=1 delims== " %%a in ("%%~l"
        ) do if /i "%%~a"=="Param_to_change" (
            >>"%config%" echo(Param_to_change=%Value_to_change%
        ) else (
            >>"%config%" echo(%%l
        )

        type "%config%"

        endlocal

    This works as expected!

    What am I missing!?.

    Thank you very much for your guidance and help!

    • Changed type Bill_Stewart Saturday, June 24, 2017 6:25 PM
    • Moved by Bill_Stewart Saturday, June 24, 2017 6:26 PM This is not "fix/edit/rewrite gallery script for me" forum
    Wednesday, April 26, 2017 11:18 AM

All replies

  • I doubt anyone is going to help you rewrite your shell script (cmd.exe batch file) so that it "works" (however you define that). That's not the purpose of this forum.

    It would be a much better idea to rewrite the logic of the script using PowerShell instead of trying to get this done in the tortured batch language syntax.


    -- Bill Stewart [Bill_Stewart]

    Wednesday, April 26, 2017 2:12 PM