Найти и извлечь текст из существующего текстового файла - PullRequest
1 голос
/ 17 января 2012

Мне нужно иметь возможность извлекать данные из существующего текстового файла.Структура текстового файла выглядит примерно так ...

this line contains a type of header and always starts at column 1
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in

this line contains a type of header and always starts at column 1
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in

this line contains a type of header and always starts at column 1
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in

this line contains a type of header and always starts at column 1
     this line contains other data and is always tabbed in
     this line contains other data and is always tabbed in

Как видите, текстовый файл разбит на части.Всегда есть одна строка заголовка, за которой следует случайное число других строк данных, и между разделами всегда есть пустая строка.К сожалению, нет никакой рифмы или причины для схемы именования разделов заголовка или данных, содержащихся в других строках данных ... только вышеупомянутая структура является несколько последовательной.Данные, которые мне нужно искать, расположены в одной из других строк данных, только в одном из разделов, которые могут быть расположены в любом месте текстового файла.Я могу использовать команду НАЙТИ, чтобы найти текст, который мне нужно найти, но как только я это сделаю, мне нужно будет извлечь весь раздел в новый текстовый файл.Я не могу понять, как подняться на столько строк до первой предыдущей пустой строки, затем перейти к следующей следующей пустой строке и извлечь все промежуточное.Имеет ли это смысл?К сожалению, VBScript просто не подходит для этого приложения, иначе с ним уже давно покончено.Есть идеи?Thanx.

Ответы [ 2 ]

1 голос
/ 18 января 2012

Программа ниже читает строки файла и сохраняет строки одного раздела в векторе, одновременно проверяя, находится ли текст поиска внутри текущего раздела. Когда раздел заканчивается, если искомый текст был найден, текущий раздел выводится как результат; в противном случае процесс переходит к следующему разделу.

@echo off
setlocal EnableDelayedExpansion
set infile=input.txt
set outfile=output.txt
set "search=Any text"
set textFound=
call :SearchSection < %infile% > %outfile%
goto :EOF

:SearchSection
   set i=0
   :readNextLine
      set line=
      set /P line=
      if not defined line goto endSection
      set /A i+=1
      set "ln%i%=!line!"
      if not "!ln%i%!" == "!line:%search%=!" set textFound=True
   goto readNextLine
   :endSection
   if %i% == 0 echo Error: Search text not found & exit /B
if not defined textFound goto SearchSection
for /L %%i in (1,1,%i%) do echo !ln%%i!
exit /B

Ограничения этой программы те же, что и у dbenham для своей программы.

1 голос
/ 18 января 2012
@echo off
setlocal enableDelayedExpansion
set input="test.txt"
set output="extract.txt"
set search="MY TEXT"

::find the line with the text
for /f "delims=:" %%N in ('findstr /n /c:!search! %input%') do set lineNum=%%N
set "begin=0"

::find blank lines and set begin to the last blank before text and end to the first blank after text
for /f "delims=:" %%N in ('findstr /n "^$" %input%') do (
  if %%N lss !lineNum! (set "begin=%%N") else set "end=%%N" & goto :break
)
::end of section not found so we must count the number of lines in the file
for /f %%N in ('find /c /v "" ^<%input%') do set /a end=%%N+1
:break

::extract the section bracketed by begin and end
set /a count=end-begin-1
<%input% (
  rem ::throw away the beginning lines until we reach the desired section
  for /l %%N in (1 1 %begin%) do set /p "ln="
    rem ::read and write the section
    for /l %%N in (1 1 %count%) do (
      set "ln="
      set /p "ln="
      echo(!ln!
    )
)>%output%

Ограничения для этого решения:

  • Строки должны заканчиваться <CR><LF> (стиль Windows)
  • Строки должны быть <= 1021 байт (не включая *)1008 *) </li>
  • Конечные управляющие символы будут убраны из каждой строки

Если существуют проблемы с ограничениями, можно написать менее эффективный вариант, который читает раздел с использованием FOR / F вместоSET / P

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...