Reputation: 3
Good day, I want to know how do I create a batch script that searches through a text file that contains multiple lines that start with *==============
. I wish for it to find the last occurrence of a line like this and then only use everything thereafter in the rest of the script.
Currently I use for /F "tokens=*" %%A in (%file%.txt) do ( [process] %%A )
to scan in each line.
Any ideas?
Thanks
Upvotes: 0
Views: 1154
Reputation: 1534
I came across this answer whilst searching for a solution to effectively the same problem. MichaelS's answer above got me on the right track; there were just a few typos in that stopped it working however. For future searchers, this is a working version:
SETLOCAL EnableDelayedExpansion
for /F "tokens=*" %%A in (%file%.txt) do (
SET currentline=%%A
SET currentstring=!currentline:~0,15!
IF !currentstring!==*============== (
TYPE NUL>tempFile.txt
) ELSE (
ECHO %%A>>tempFile.txt
)
)
Upvotes: 0
Reputation: 67216
You may use findstr
command to find the lines that start with *==============
and get the number of the last one, and use such number in skip
option of for
command:
rem Get the line number of the last line that start with "*=============="
for /F "delims=:" %%a in ('findstr /N "^\*==============" %file%.txt') do set lastLine=%%a
rem Process the file from the next line to that one on
for /F "skip=%lastLine% tokens=*" %%A in (%file%.txt) do ( [process] %%A )
Upvotes: 0
Reputation: 6032
You could scan the file for this line (as you are doing it now) but instead of processing it directly you could store the lines below *==============
somehow (eg. in a temp file). If you find another line like *==============
you delete everything you have saved till then and start saving the lines below again. You will end up at the last line containing *==============
save everything below it and reach the end of file so only the last block will remain in the temp file. Now you can process the file and be sure that it contains only data below the last *==============
line.
The code would look something like this:
SETLOCAL EnableDelayedExpansion
for /F "tokens=*" %%A in (%file%.txt) do (
SET currentline = %%A
SET currentstring=!currentstring~0,15!
IF !currentstring!==*============== (
TYPE NUL > tempFile.txt
) ELSE (
ECHO %%A>>tempFile.txt
)
)
::process the data from tempFile.txt
Upvotes: 1