0
votes

I'm interested in writing a batch script that will copy the final block of text in a .txt file that has numerous other blocks of text. Think of the log file for the executions of a script, but without any consistent content or length. Each entry is delimited by an empty line.

So for the following document, I would only want to select and copy the final paragraph:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The text itself can vary in length. The only reliable indicator of what I need is that it will be everything following the final blank line in the document -- in this case, everything following "Duis aute..."

I'm thinking that the outline of the script is going to be something like this, but I'm not at all familiar with batch. Many thanks for any help you can provide!

SET FOO
FOR /F "delims=" %%G IN (somefile.txt) DO
(IF "%%G"=="" (SET FOO="" )
ELSE (SET FOO==%%G + %FOO%))
ECHO %FOO%>whatever.txt
2

2 Answers

2
votes
@echo off
setlocal

rem Get the line number of the last empty line
for /F "delims=:" %%a in ('findstr /N "^$" somefile.txt') do set "skip=skip=%%a"

rem Show all lines after it
for /F "%skip% delims=" %%a in (somefile.txt) do echo %%a
0
votes

You could do this:

@echo off
setlocal EnableDelayedExpansion
SET "FOO="
type "file.txt" > "file.txt.tmp"
for /f "tokens=1* delims=:" %%A in ('findstr /n "^" "file.txt.tmp"') do if [%%B]==[] (SET "FOO=") else (SET "FOO=!FOO!%%B")
del "file.txt.tmp"
>filepara.txt echo %FOO%

This has just one downside, it doesn't echo linebreaks from the original paragraph to the text file.

EDIT:

I found a way to do this that keeps the newlines, by creating a variable containing a newline:

@echo off
setlocal EnableDelayedExpansion
set LF=^


SET "FOO="
type "file.txt" > "file.txt.tmp"
for /f "tokens=1* delims=:" eol=¬ %%A in ('findstr /n "^" "file.txt.tmp"') do if [%%B]==[] (SET "FOO=") else (SET "FOO=!FOO!%%B!LF!")
del "file.txt.tmp"
>temp.txt echo !FOO!
more temp.txt > paragraph.txt
del temp.txt

Note: You need the two blank lines after set LF for this to work!