batch-filestring-substitutiondrive-letter

Batch file change a drive letter string in a log file


trying to replace drive designation inside Idrive log files using a batch. Amateur programmer trying to understand batch files for years but still don't get advanced techniques. I suspect the '\' backslash needs to be escaped but nothing I try works.

Sample Log input:

[C:\Users\rh56\Music\desktop.ini]
[D:\clients\]
[D:\Orion\]
[D:\rigel\]
[SUCCESS] [03/06/2020 5:02:19] [[Full Backup]  C:\stuff\2019-01-14 11_54_14-Cartoon Caption Contest _ The New Yorker.png][Size: 191.03 KB]]
[SUCCESS] [03/06/2020 5:02:19] [[Full Backup][C:\junk\2019-05-01 20_22_26-Greenshot.png][Size: 384.27 KB]]
[SUCCESS] [03/06/2020 5:02:20] [[Full Backup]C:\arbitrage\EuroYen30day\2019-05-01 20_23_06-Window.png][Size: 271.33 KB]]

Desired Output: (notice substituting M:\ for C:\ )

[M:\Users\rh56\Music\desktop.ini]
[D:\clients\]
[D:\Orion\]
[D:\rigel\]
[SUCCESS] [03/06/2020 5:02:19] [[Full Backup]  M:\stuff\2019-01-14 11_54_14-Cartoon Caption Contest _ The New Yorker.png][Size: 191.03 KB]]
[SUCCESS] [03/06/2020 5:02:19] [[Full Backup][M:\junk\2019-05-01 20_22_26-Greenshot.png][Size: 384.27 KB]]
[SUCCESS] [03/06/2020 5:02:20] [[Full Backup][M:\arbitrage\EuroYen30day\2019-05-01 20_23_06-Window.png][Size: 271.33 KB]]

My code:

  set vSearch=C:\\ & set vReplace=M:\\
  setlocal enableextensions disabledelayedexpansion
  ::https://stackoverflow.com/questions/23075953/batch-script-to-find-and-replace-a-string-in-text-file-without-creating-an-extra/23076141
echo. & echo DEBUG DEBUG DEBUG & pause & echo.
    set "vtextFile=C:\idriveLogChecker\molly.log"
    for /f "delims=" %%i in ('type "%vtextFile%" ^& break ^> "%vtextFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%vtextFile%" echo(!line:%vSearch%=%vReplace%!
        endlocal
    )
echo. & echo DEBUG DEBUG DEBUG & pause & net use & set v & echo on & echo. & cmd /K

This all seems very convoluted—is there some easier highly automated way to do this with minimal learning curve? Thank you for your help


Solution

  • Your code works fine for me - when I correct just one line:

    set "vSearch=C:\" & set "vReplace=M:\"
    

    The \ hasn't to be escaped (another \ would be wrong anyway. The escape char is ^) and more important: Your original line sets the first variable to C:\\<SPACE>, so there is nothing to be replaced.

    Note the position of the quotes - they don't become part of the variable name or value, but is the recommended syntax and avoids stray spaces and is safe against some poisonous characters like <>&|.