我有两个文本文件,我逐行比较。
文本文件如下所示:
version_local.txt | version_server.txt
----------------- | ------------------
APP1 V5 | APP1 V5
APP2 V5 <--- | APP2 V8 <---
APP3 V4 | APP3 V4
我当前的解决方案在文本文件的底部创建了一个新行,但它没有替换确切的行。
@echo off
set "file=C:\APPS\version_master.txt"
set "ROOT_URL_SERVER=\\SERVER-SQL1\ClientDatabase\version_master.txt"
set "ROOT_URL_LOCAL=C:\APPS\version_master.txt"
FOR /F "delims=" %%a in ('FINDSTR /rc:"\<APP2\>" %ROOT_URL_SERVER%') DO SET @Check_Server=%%a
FOR /F "delims=" %%a in ('FINDSTR /rc:"\<APP2\>" %ROOT_URL_LOCAL%') DO SET @Check_Local=%%a
ECHO %@Check_Local%
ECHO %@Check_Server%
ECHO ==============
REM Call Function to Update Versions
call:Update_Version_Local
:end
pause
::--------------------------------------------------------
::-- Function Update_Version_Local
::--------------------------------------------------------
:Update_Version_Local
setlocal DisableDelayedExpansion
for /f %%i in ('type "%file%"^|find /c /v ""') do set "current=%%i"
<"%file%" >"%file%.tmp~" (
for /f "delims=" %%i in ('type "%file%"^|findstr /n "^"') do (
set "line=%%i"
setlocal EnableDelayedExpansion
for /f "delims=:" %%j in ("!line!") do if %%j EQU %current% (
echo(!@Check_Server!
) else (
echo(!line:*:=!
)
endlocal
)
)
move /y "%file%.tmp~" "%file%"
goto:eof
输出
version_local.txt
-----------------
APP1 V5
APP2 V5
APP3 V4
APP2 V8 <---
我的目的是覆盖此示例中的第二行,如下所示:
预期输出
version_local.txt
-----------------
APP1 V5
APP2 V8 <---
APP3 V4
答案 0 :(得分:2)
这样的事情应该做(或者至少给你一个很好的起点):
@echo off
setlocal
del version_result.txt 2>nul
for /f "tokens=1,2" %%a in (version_local.txt) do (
REM %%a=AppName
REM %%b=LocalVer
for /f "tokens=2" %%c in ('type version_server.txt ^|findstr /bic:"%%a"') do (
REM %%c=ServerVer
echo DEBUG [[ %%a, %%b, %%c ]]
if "%%b" neq "%%c" call :different "%%~a" "%%~b" "%%~c"
(if errorlevel 1 (
REM write local version:
echo %%a %%b
) else (
REM write updated server version:
echo %%a %%c
)) >> version_result.txt
)
)
echo ----
type version_result.txt
goto :eof
:different
echo Application %~1 has local version %~2 but server version %~3
echo [insert code to update]
REM if successful:
exit /b 0
REM if not successful:
exit /b 1
注意:两个文件中的应用程序名称应该相同(仅忽略其中一个文件中的应用程序;顺序无关紧要)。结果订单将与本地文件中的订单相同。