如何使用Batch从文件中获取文本块

时间:2012-06-22 21:39:24

标签: parsing text batch-file

我试图从我已经创建的文件中获取一个文本块,并将该信息存储到一个新文件中。要解析的文本文件ID设置如下:

HostName:xxxxxx

(8行左右的信息)

HostName:xxxxxx

我遇到的最大问题是在文本块之间我特意寻找“admin”这个词。我能够找到并返回带有管理单词的行,现在我需要编写一个循环来获取上面和下面的信息,如果在该文本块中找到单词admin(我将使用空行作为在我的文件中保持一致的分隔符。)

我已经写了几个for循环,但没有一个给我什么ID。任何帮助将不胜感激 感谢

1 个答案:

答案 0 :(得分:2)

以下程序可以满足您的需求:

@echo off
setlocal EnableDelayedExpansion
rem Create the info removing empty lines
(for /F "delims=" %%a in ('schtasks /query /fo list /v') do echo %%a) > schtasks.txt
rem Add an additional "HostName:" line at end as delimiter
echo HostName: >> schtasks.txt
rem Create a vector of number of lines containing "HostName:"
set i=0
for /F "delims=:" %%a in ('findstr /N "HostName:" schtasks.txt') do (
   set /A i+=1
   set header[!i!]=%%a
)
rem Seek for the LINES containing "admin"
for /F "delims=:" %%a in ('findstr /N /I "administrator" schtasks.txt') do (
   rem Seek for the NEXT section that contains "admin" line
   for /L %%i in (1,1,%i%) do if %%a gtr !header[%%i]! set thisSection=%%i
   rem Locate that section
   set /A start=header[!thisSection!], nextSection=thisSection+1
   set /A end=header[!nextSection!]-1
   rem ... and show it
   set line=0
   for /F "delims=" %%a in (schtasks.txt) do (
      set /A line+=1
      if !line! geq !start! if !line! leq !end! echo %%a
   )
   echo ----------------------------------------------
)
del schtasks.txt

PS - 当然MS-DOS / Windows Batch是一种编程语言!