将行存储在动态文本中的变量中

问题描述 投票:0回答:1

我正在尝试存储文本文件中的每一行以进行一些处理。文本文件是动态的,它将随着更多的搜索条目而增长。问题是,如果原始文本文件有10个条目,它将仅循环10次,即使尚未完成循环,也会添加更多条目。是否可以循环其他新条目在同一个循环中?

@echo off

SETLOCAL enabledelayedexpansion

set /p search_parameter="Type your search: "

rem run grep seach commmand
grep -nri %search_parameter% --colour --include=*.{c,h} > text.txt

rem filter required lines into new text file
type text.txt | findstr /I "#include" | findstr /V "examples DELIVERY_REL" > text2.txt

set /A count=0
rem read text file line-by-line
for /F "tokens=* delims=" %%G in (text2.txt) do (
set /A count+=1
set "line=%%G"
for /f "delims=:" %%i in ("!line!") do set "line=%%~nxi"

if NOT "!line!"=="!line:.h=!" (
grep -nri !line! --colour --include=*.{c,h} >> text2.txt
rem echo %%G
)
echo count: !count!
echo line: !line!
)
rem type text2.txt | findstr /I "#include" | findstr /V "examples DELIVERY_REL" > text3.txt

pause

echo on
batch-file
1个回答
0
投票

从我的头顶上方,我将反复读取文件,跳过已经处理的行,直到到达结尾为止。我将给出一个简短的示例代码:

@echo off
setlocal enabledelayedexpansion

set cnt=1

:loopfor
for /F "%skip% tokens=* delims=" %%G in (text2.txt) do (
   echo %%G
   set "skip=skip=%cnt%"
   set /a cnt+=1
   goto :loopfor
)

echo We make it here when there are no lines in the file that we haven't already processed.

需要变量skip,因为for /f "skip=0" ...会产生错误。解释:基本上,实际的for循环读取“ next”行,增加一个计数器,并通过GO将[for循环]标签的TO循环并中断for循环。我们使用递增的cnt变量跟踪“下一条”行,然后跳过该行数。 (巨大的)缺点是一遍又一遍地读取该文件。现在,我可能会使用这样的子例程:

@echo off
setlocal enabledelayedexpansion

set cnt=1

:loopfor
for /F "%skip% tokens=* delims=" %%G in (text2.txt) do (
   call :process "%%~G"
   goto :loopfor
)

echo We make it here when there are no lines in the file that we haven't already processed.

goto :eof

:process
echo %~1
set "skip=skip=%cnt%"
set /a cnt+=1
goto :eof

echo we made it here.

我将尝试将此概念引入您的代码中,但是您必须对其进行彻底的测试。

@echo off

SETLOCAL enabledelayedexpansion

set /p search_parameter="Type your search: "

rem run grep seach commmand
grep -nri %search_parameter% --colour --include=*.{c,h} > text.txt

rem filter required lines into new text file
type text.txt | findstr /I "#include" | findstr /V "examples DELIVERY_REL" > text2.txt

rem you might be able to use the variable count, but I'll add cnt anyway
set /A count=0
rem read text file line-by-line

rem Adding code starting here

set cnt=0
set skip=
:loopfor
for /F "%skip% tokens=* delims=" %%G in (text2.txt) do (
   set /A count+=1
   set "line=%%G"
   for /f "delims=:" %%i in ("!line!") do set "line=%%~nxi"

   if NOT "!line!"=="!line:.h=!" (
      grep -nri !line! --colour --include=*.{c,h} >> text2.txt
      rem echo %%G
   )
   echo count: !count!
   echo line: !line!
   set "skip=skip=%cnt%"
   set /a cnt+=1
   goto :loopfor
)
rem type text2.txt | findstr /I "#include" | findstr /V "examples DELIVERY_REL" > text3.txt

pause

echo on
© www.soinside.com 2019 - 2024. All rights reserved.