找到&使用for / f替换字符串if语句和变量

时间:2016-09-13 12:18:21

标签: batch-file find-replace

我编写了一个批处理文件,我想用另一个.txt文件中的字符串覆盖键字符串。

目前它完全复制了新的File.txt文件,但没有用OldFile.txt文件中的字符串替换字符串。

File.txt文件中的字符串示例:

  

...

     

#密码
  PWORD =

     

#AccountName
  帐户=

     

#TownName
  镇=

     

#Postcode
  邮政编码=

     

#LocationChangedDate
  LocationChanged =

我要替换的OldFile.txt文件中的字符串示例:

  

...

     

#密码
  PWORD = ABC

     

#AccountName
  帐户= 123

     

#TownName
  镇= LDN

     

#Postcode
  邮政编码= WS77TP

     

#LocationChangedDate
  LocationChanged = 01/01/2015

有人可以指出我正确的方向或解释我犯错的地方吗?

@echo off

setlocal disableDelayedExpansion

::Variables
set InputFile=F:\EXCHANGE\3\Machine\File.txt
set OutputFile=F:\EXCHANGE\3\File-New.txt
set CopyFile=F:\EXCHANGE\3\OldMachine\OldFile.txt

set _strFindPword=Pword=.*
for /F "delims=" %%A in ('findstr /x "Pword=.*" %CopyFile%') do set _strInsertPword=%%A

echo.%_strInsertPword%

set _strFindAccount=Account=.*
for /F "delims=" %%B in ('findstr /x "Account=.*" %CopyFile%') do set _strInsertAccount=%%B

echo.%_strInsertAccount%

set _strFindTown=Town=.*
for /F "delims=" %%C in ('findstr /x "Town=.*" %CopyFile%') do set _strInsertTown=%%C

echo.%_strInsertTown%

set _strFindLocationChanged=LocationChanged=.*
for /F "delims=" %%D in ('findstr /x "LocationChanged=.*" %CopyFile%') do set _strInsertLocationChanged=%%D

echo.%_strInsertLocationChanged%

set _strFindPostcode=Postcode=.*
for /F "delims=" %%E in ('findstr /x "Postcode=.*" %CopyFile%') do set _strInsertPostcode=%%E

echo.%_strInsertPostcode%


(
  for /F "delims=" %%L in ('findstr /n "^" "%InputFile%"') do (
    set "line=%%L"
    setlocal EnableDelayedExpansion
    set "line=!line:*:=!"
    if "%%L" equ "_strFindPword" (echo.!_strInsertPword!) else (
       if "%%L" equ "%_strFindAccount%" (echo.!_strInsertAccount!) else (
          if "%%L" equ "%_strFindTown%" (echo.!_strInsertTown!) else (
             if "%%L" equ "%_strFindLocationChanged%" (echo.!_strInsertLocationChanged!) else (
                if "%%L" equ "%_strFindPostcode%" (echo.!_strInsertPostcode!) else (echo.!line!)
             )
          )
       )
    )
    endlocal
  )
) > "%OutputFile%"

del %InputFile% 

ren %OutputFile% File.txt



pause

4 个答案:

答案 0 :(得分:3)

我想我终于明白了......

它的作用:

  • 它遍历 OldFile.txt 内容,搜索标记,如果发现它们存储在环境变量中以便在嵌套步骤中使用(例如_PWD标记(变量)它的值为Pword=,它会创建一个_PWDCONTENTS变量,其内容为Pword=ABC
  • 通过 File.txt 内容,搜索相同的标记,如果找到一个标记,则相应的CONTENTS变量将转储到 OutFile.txt ,否则原始行。因为这发生在内部for循环中,我不得不添加一些额外的逻辑(_WROTE var)以避免多次写入相同的行。

备注

  • 假设(除了做它应该做的事情之外)是“可配置的”(代码很复杂,它正朝着 meta :)前进,如果你愿意的话,意思是如果标记之间存在变化,则代码不应更改(代码更改,但仅在变量定义中不在功能部分)。让我详细说明一下:

    • 如果您不再需要替换Town=字符串,那么您只需从_TOWN移除_ALLset _ALL=_PWD _ACCT _POST _LOC
    • 反过来说:如果你想添加一些其他标签(我们称之为 Name ),你必须创建一个新的环境变量:set _NAME=Name=并将其添加到_ALL }:set _ALL=_PWD _ACCT _TOWN _POST _LOC _NAME
  • 作为间接后果,我没有专注于性能,所以它可能会运行缓慢。无论如何,我试图将磁盘访问(速度极慢)保持在最低限度(例如,当有2 for循环时,迭代文件内容的循环 - 假设每次迭代都需要磁盘访问;这可能不是真的, Win 有IO缓冲 - 它是外部的。)

  • 我“注释”了文件中的最后一行,以避免覆盖原始文件。如果需要这种行为,只需删除开头的rem

这是批处理代码:

@echo off
setlocal enabledelayedexpansion

set _INFILE="File.txt"
set _OUTFILE="NewFile.txt"
set _OLDFILE="OldFile.txt"


set _PWD=Pword=
set _ACCT=Account=
set _TOWN=Town=
set _POST=Postcode=
set _LOC=LocationChanged=
set _ALL=_PWD _ACCT _TOWN _POST _LOC

echo Parsing old file contents...

for /f "tokens=*" %%f in ('type !_OLDFILE!') do (
    for %%g in (!_ALL!) do (
        echo %%f | findstr /b /c:!%%g! 1>nul
        if "!errorlevel!" equ "0" (
            set %%gCONTENTS=%%f
        )
    )
)

copy nul %_OUTFILE%
echo Merging the old file contents into the new file...
set _WROTE=0

for /f "tokens=*" %%f in ('findstr /n "^^" !_INFILE!') do (
    set _TMPVAR0=%%f
    set _TMPVAR0=!_TMPVAR0:*:=!
    for %%g in (!_ALL!) do (
        echo !_TMPVAR0! | findstr /b /c:!%%g! 1>nul
        if "!errorlevel!" equ "0" (
            echo.!%%gCONTENTS!>>!_OUTFILE!
            set _WROTE=1
        )
    )
    if "!_WROTE!" equ "0" (
        echo.!_TMPVAR0!>>!_OUTFILE!
    ) else (
        set _WROTE=0
    )
)

rem copy /-y %_OUTFILE% %_INFILE%

@ EDIT0 :使用@StevoStephenson建议(作为问题代码段的一部分),我将(第二个)外部for循环替换为('findstr /n "^^" !_INFILE!')以包含空行,所以第3条评论不再适用(删除)。还进行了一些小的更改,以允许在其路径中包含 SPACE 的文件。

答案 1 :(得分:1)

它并不完美,但这对你来说可能没问题:

@Echo Off
Setlocal EnableExtensions DisableDelayedExpansion

(Set InputFile=F:\EXCHANGE\3\Machine\File.txt)
(Set OutputFile=F:\EXCHANGE\3\File-New.txt)
(Set CopyFile=F:\EXCHANGE\3\OldMachine\OldFile.txt)

For /F "Delims=" %%I In (
    'FindStr/B "Pword= Account= Town= LocationChanged= Postcode=" "%CopyFile%"'
    ) Do Set %%I

(For /F "Tokens=1-2* Delims=]=" %%I In ('Find /V /N ""^<"%InputFile%"') Do (
    Echo(%%J|FindStr/B # || (If Defined %%J (Call Echo=%%J=%%%%J%%) Else (
            If "%%J" NEq "" (Echo=%%J=%%K) Else (Echo=)))))>%OutputFile%
Timeout -1
EndLocal
Exit/B

我已离开删除并重命名,以便在最后添加。

答案 2 :(得分:0)

也许它就像这样

set CopyFile=oldfile.txt
set InputFile=newfile.txt

set str_search="Pword"
for /f "delims=" %%i in ('findstr %str_search% %copyfile%') do set str_replace=%%i
set str_replace="%str_replace%"
echo %str_search%
echo %str_replace%
pause

CALL :far %InputFile% %str_search% %str_replace%
EXIT /B 0

:far
setlocal enableextensions disabledelayedexpansion

set "search=%2"
set "replace=%3"
::remove quotes
set search=%search:"=%
set replace=%replace:"=%
echo %search%
echo %replace%

set "textFile=%1"

for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    >>"%textFile%" echo(!line!
    endlocal
)
EXIT /B 0

for /f "delims=" %%i in ('findstr %str_search% %copyfile%') do set str_replace=%%i,您使用具有str_replace所需信息的变量编写该行。 之后,程序调用一个嵌入式查找和替换函数(:far),我从Batch script to find and replace a string in text file without creating an extra output file for storing the modified file无耻地偷走了这个函数 此函数查找字符串“Pword”并将其替换为旧文件中的行find。

注意: 这并不能完全解决您的问题,因为您的新文件必须是这样的。

#Password
Pword

所以,如果你松开=,它就会起作用,否则就不会。我希望这可以帮助您解决问题。

答案 3 :(得分:0)

此解决方案应该比其他解决方案快得多 它还会保留包含!^

的空行和行

只需要一次findstr来收集所有单词的旧值 第二个findstr确定infile中需要更新的所有行(按行号)。

@echo off
setlocal EnableDelayedExpansion

set "_INFILE=File.txt"
set "_OUTFILE=NewFile.txt"
set "_OLDFILE="OldFile.txt"

set "_WORDS=Pword= Account= Town= Postcode= LocationChanged="

REM *** get all values for the key words
for /F "tokens=1,* delims==" %%L in ('findstr "!_WORDS!" "!_OLDFILE!"') do (
    for /F %%S in ("%%L") do (
        set "word[%%S]=%%M"
    )
)

REM *** Find all lines which needs an update
set wordIdx=0
for /F "tokens=1,2,* delims=:= " %%1 in ('findstr /n "!_WORDS!" "!_INFILE!"') do (
    set "lines[!wordIdx!].line=%%1"
    set "lines[!wordIdx!].word=%%2"
    set "replace=!word[%%2]!"
    set "lines[!wordIdx!].replace=!replace!"
    set /a wordIdx+=1
)

REM *** copy the infile to the outfile
REM *** Replace only the lines which are marked by line numbers
echo Parsing old file contents...
set nextWordIdx=0
set /a searchLine=lines[!nextWordIdx!].line
set lineNo=0
setlocal DisableDelayedExpansion
(
    for /f "tokens=*" %%L in ('findstr /n "^" "%_INFILE%"') do (
        set "line=%%L"
        set /a lineNo+=1
        setlocal EnableDelayedExpansion
        set "line=!line:*:=!"
        if !lineNo! equ !searchLine! (
            (echo(!line!!lines[0].replace!)
            set /a nextWordIdx+=1
            for /F %%R in ("!nextWordIdx!") do (
                endlocal
                set /a nextWordIdx=%%R
                set /a searchLine=lines[%%R].line
            )
        ) ELSE (
            (echo(!line!)
            endlocal
        )
    )
) > "!_OUTFILE!"