我有以下蝙蝠代码来查找一组文本文件中的字符,并在找到的行后插入一个新行:
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 :(得分: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
,有时两次,则程序运行速度比使用内部命令时要慢。如果文件很大,或文件数量很大,两种方法之间的区别就会非常明显......
答案 1 :(得分: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%"
答案 2 :(得分: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
的测试设置保留到位)