我有一个 .sql 文件,想要替换所有行,如下所示:
VALUES (12,
VALUES (24,
VALUES (9999,
与
VALUES (NULL,
我已经尝试过这样,但正则表达式似乎不起作用,并且输出没有改变
@echo off
setlocal enabledelayedexpansion
set "replacement=VALUES (NULL,"
set "regex=VALUES \(\d+,"
set "output_file=updated_sql_dump.sql"
(for /f "delims=" %%i in ('type "MONITORING-schema.sql" ^| findstr /n "^"') do (
set "line=%%i"
echo !line! | findstr /r /c:"%regex%" >nul && (
echo !line:%search%=%replacement%!
) || (
echo !line:*:=!
)
))
我提出以下建议:
@ECHO OFF
SETLOCAL enabledelayedexpansion
:rerun
REM Remove the result file from a previous run
SET inputFile=inputFile.txt
SET outputFile=outputFile.txt
DEL %outputFile%
REM create a test file and fill with some data
ECHO VALUES (12,>%inputFile%
ECHO VALUES (24,>>%inputFile%
ECHO Some other line>>%inputFile%
ECHO VALUES (9999,>>%inputFile%
ECHO Input file:
ECHO.
TYPE %inputFile%
ECHO.
REM Define a constant string
SET constString=VALUES (
ECHO Constant string: "%constString%"
REM Define a replacement string
SET replaceString=NULL,
ECHO Replacement string: "%replaceString%"
ECHO.
for /f "delims=" %%a in (%inputFile%) do (
SET lineInFile=%%a
ECHO Given line: "!lineInFile!"
SET dynamicStrig=!lineInFile:%constString%=!
ECHO Dynamic string: "!dynamicStrig!"
IF "!lineInFile!" == "!dynamicStrig!" (
REM No constant string was found. Input line will be output line
SET resultString=!lineInFile!
) ELSE (
REM This is the tricky part. Replace the dynamic part of the line with the replacement string
for %%b in ("!dynamicStrig!") do set "resultString=!lineInFile:%%~b=%replaceString%!"
)
ECHO New line: "!resultString!"
REM Append the line to the output file
ECHO !resultString!>>%outputFile%
)
ECHO.
ECHO Output file:
ECHO.
TYPE %outputFile%
ECHO.
REM for test purposes rerun the script
pause
GOTO rerun
输出:
重要的一行是
for %%b in ("!dynamicStrig!") do set "resultString=!lineInFile:%%~b=%replaceString%!"