how to search and replace case sensitive string using batch

前端 未结 3 1089
旧时难觅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:15

    We all know that Batch files have multiple restrictions, so the creation of general purpose solutions is difficult. Because of this, I always try to fullfill the particular requirements of a certain given problem first. If this is possible, then the limitations of Batch to provide a more general solution for other similar problems that are NOT currently being requested by someone don't matters, right?

    The Batch file below do a case-sensitive replacement of one string by another one and it is very fast, but it fail in lines that contain the original string written MORE THAN ONCE in different case combinations, including the target one. I think this method is enough for most users that have this requirement.

    @echo off
    setlocal EnableDelayedExpansion
    
    set /P "file=Enter file name: "
    set /P "OldStr=Enter original text: "
    set /P "NewStr=Enter new text: "
    
    rem Get list of numbers of matching lines to replace
    set n=0
    for /F "delims=:" %%a in ('findstr /N /C:"%OldStr%" "%file%"') do (
       set /A n+=1
       set replace[!n!]=%%a
    )
    if %n% equ 0 (
       echo Original text not found in file
       goto :EOF
    )
    set /A n+=1
    set replace[%n%]=0
    
    rem Process all lines in the file
    setlocal DisableDelayedExpansion
    set i=1
    (for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%file%"') do (
       set line=
       set "line=%%b"
       setlocal EnableDelayedExpansion
       rem If this line have the original string...
       for %%i in (!i!) do if %%a equ !replace[%%i]! (
          rem ... replace it and advance to next matching line number
          echo !line:%OldStr%=%NewStr%!
          endlocal & set /A i=%%i+1
       ) else (
          echo(!line!
          endlocal
       )
    )) > "%file%_new.txt
    rem If you want to replace the original file, remove REM from next line:
    REM move /Y "%file%_new.txt" "%file%"
    

    For example, this input file:

    This line is not changed: Rise. 
    No problem with special characters: & | < > ! " ^ 
    This line is changed: rise
    This line is not changed: RISE
    This line is incorrectly changed: Rise & rise
    

    with a replacement of "rise" by "New Text", produce:

    This line is not changed: Rise. 
    No problem with special characters: & | < > ! " ^ 
    This line is changed: New Text
    This line is not changed: RISE
    This line is incorrectly changed: New Text & New Text
    

提交回复
热议问题