How to replace Strings in Windows Batch file

前端 未结 4 560
误落风尘
误落风尘 2020-12-22 08:20

I would like to replace the following String in a file:

android:versionName=\"anyStringHere\" >

*anyStringHere represents any possible s

4条回答
  •  被撕碎了的回忆
    2020-12-22 09:01

    Not even close to the fastest option, and not 100% bulletproof, but this is pure batch and will handle spacing and indentation while do the replacement.

    @echo off
        setlocal enableextensions disabledelayedexpansion
    
        rem File to process
        set "file=data.txt"
    
        rem How to find lines
        set "match=public static String CONST = \"abc\";"
    
        rem String to replace and replacement
        set "findStr=abc"
        set "replaceStr=def"
    
        rem temporary file to work with lines
        set "tempFile=%temp%\repl.tmp"
    
        rem All the output goes into the temporary file
        (
    
            rem Process input file extracting non matching lines
            for /f tokens^=^1^*^ delims^=^:^ eol^= %%a in ('findstr /n /v /c:"%match%" ^< "%file%"') do (
                set /a "n=1000000+%%a" 
                setlocal enabledelayedexpansion
                < nul set /p "n=!n!"
                endlocal
                echo :%%b
            )
    
            rem Process input file extrancting matching lines and changing strings
            for /f tokens^=^1^*^ delims^=^:^ eol^= %%a in ('findstr /n /c:"%match%" ^< "%file%"') do (
                set /a "n=1000000+%%a" 
                set "data=%%b"
                setlocal enabledelayedexpansion
                set "data=!data:%findStr%=%replaceStr%!"
                echo !n!:!data!
                endlocal
            ) 
        )> "%tempFile%"
    
        rem Sort the output file to get the final file
        (for /f tokens^=^1^*^ delims^=^:^ eol^= %%a in ('sort "%tempFile%"') do (
            if "%%b"=="" ( 
                echo.
            ) else (
                echo %%b
            )
        )) > "%file%.repl"
    

提交回复
热议问题