2014-02-21 38 views
0

我有以下蝙蝠代碼找到一組文本文件的字符,並插入找到的行之後新行:嵌套FINDSTR在bat文件的文本文件

for /R "%SrcFolder%" %%a in ("*.txt") do (
    (for /f "usebackq delims=" %%h in ("%%a") do (
    echo %%h 
    echo "%%h"|findstr /I "{" > nul & if not errorlevel 1 (
     echo NEW LINE 
    ) 
) 

現在我要僱用的另一findstr檢查當前行(%% h)的前一行是否有特定字符(如「B」),如果是,則跳過插入新行。

我希望我能清楚地問清楚。 有什麼建議嗎? 謝謝。

回答

0

試試這個:

@ECHO OFF &SETLOCAL disableDelayedExpansion 
SET "InFileName=infile.txt" 
SET "OutFileName=outfile.txt" 
(FOR /f "delims=" %%a IN ('FINDSTR /n "^" "%InFileName%"') DO (
    SET "PrimLine=%%a" 
    SETLOCAL enableDelayedExpansion 
    SET "Line=!PrimLine:*:=!" 
    ECHO(!Line! 
    ECHO("!Line!"|FINDSTR "}" >nul && (
     SET "SecLine=!SecLine:*:=!" 
     ECHO("!SecLine!"|FINDSTR /i "B" >nul || ECHO(
    ) 
    ENDLOCAL 
    SET "SecLine=%%a" 
))>"%OutFileName%" 
1

批代碼下面你要什麼:

@echo off 
setlocal EnableDelayedExpansion 

for /R "%SrcFolder%" %%a in ("*.txt") do (
    echo File: "%%a" 
    set "prevLine=" 
    for /f "usebackq delims=" %%h in ("%%a") do (
     echo %%h 
     rem Check if current line have "{" char: 
     set thisLine=%%h 
     if "!thisLine:{=!" neq "!thisLine!" (
     rem YES: Check if previous line have "B" char: 
     if "!prevLine:B=!" equ "!prevLine!" (
      rem NO: insert the new line 
      echo NEW LINE 
     ) 
    ) 
     set "prevLine=!thisLine!" 
    ) 
    echo ------------------- 
    echo/ 
) 

然而,這種方法不使用findstr,對不起......

findstr.exe是外部命令,每次執行時都需要加載一個〜30 KB的文件。如果對文件的每一行執行findstr,有時甚至是兩次,程序運行速度會比僅使用內部命令時慢。如果文件較大或文件數量較多,這兩種方法之間的差異會很明顯......

+0

感謝您的回覆。但是,即使該行沒有「{」字符:if「!thisLine:{=!」),代碼中的這一行始終爲真neq「!thisLine!」 ( – Bipario

+0

只需在命令提示符下進行測試:輸入:'set var =這不包含左括號,然後是'if'%var:{=%「neq」%var%「echo它失敗:始終爲true,即使該var不包含左大括號,並檢查結果! – Aacini

0
@ECHO OFF 
SETLOCAL 
SET "srcfolder=.\cb4c" 

for /R "%SrcFolder%" %%a in ("*.txt") do (
SET "checkme=Y" 
for /f "usebackq delims=" %%h in ("%%a") do (
    echo %%h 
    IF DEFINED checkme (
    echo "%%h"|findstr /I "{" > NUL 
    if not errorlevel 1 (echo NEW LINE) 
) 
    echo "%%h"|findstr "B" > NUL 
    if errorlevel 1 (SET "checkme=Y") ELSE (SET "checkme=") 
) 
) 
GOTO :EOF 

(我已經離開我的測試設置的到位srcfolder