how to search and replace case sensitive string using batch

前端 未结 3 1087
旧时难觅i
旧时难觅i 2021-01-15 15:08

I want to search and replace case sensitive string

like if I have rise Rise RISE in a text file I only want to replace string \"rise\" the code below is replace a

3条回答
  •  甜味超标
    2021-01-15 16:02

    @ECHO OFF
    SETLOCAL
    SET "old=rise"
    SET "new=deflate"
    DEL newfile.txt /F /Q
    FOR /f "delims=" %%i IN ('type somefile.txt^|findstr /n "$" ') DO (
    ECHO %%i
    SET line=%%i
    CALL :replace
    )
    
    FC somefile.txt newfile.txt
    
    GOTO :eof
    
    :REPLACE
    :: first replace all characters up to the colon by nothing
    SET line=%line:*:=%
    SET "withreplacements="
    :loop
    IF NOT DEFINED line >>newfile.txt ECHO(%withreplacements%&GOTO :EOF 
    ECHO %line%|FINDSTR /b /l /c:"%old%" >NUL
    IF ERRORLEVEL 1 SET withreplacements=%withreplacements%%line:~0,1%&SET line=%line:~1%&GOTO loop
    SET withreplacements=%withreplacements%%new%
    SET remove=%old%
    :loploop
    IF DEFINED remove SET remove=%remove:~1%&SET line=%line:~1%&GOTO loploop
    GOTO loop
    

    Here's a relatively simple method. It has a marked sensitivity to certain characters, "^&|<> being the problems - perhaps some others too - but space,;%!)( seem fine.

    It reads every line by numbering usinf FINDSTR which places linenumber : at the beginning of each line

    That prefix is removed and the withreplacements line built character-by-character

    • see whether the line starts with the target replaceme string
    • If it doesn't remove the first character, place it onto the end of the string being built
    • if it does match,
      • append the replacement string
      • make a copy of the string-to-replace
      • remove the first character of the source string and the copy-to-replace until the copy-to-replace becomes empty

    and repeat until the original line becomes empty

    Yes - it's S-L-O-W. But it works. Kinda.

    Improvement suggestions welcome.

提交回复
热议问题