Page 1 of 1

Read a file in reverse-last line first

Posted: 05 Jan 2015 21:55
by Jer
Sorry if this is a dumb question. In a batch file I want to read a sorted file, DIR.DAT, which has
lines like this:
B01001001.txt
B01001002.txt
B02001001.txt
etc. (data represents book#, chapter#, page#, and used in a book reading application all done in a batch file.)

The target I am looking for is the first 3 characters, for example B22
What I want to determine is which line has the last occurrence of the target.
If I were searching for B01, for the above example data, the answer would be 2 (line 2).

Is there a reverse-file-read method?
Thanks.

Re: Read a file in reverse-last line first

Posted: 05 Jan 2015 22:47
by ShadowThief
You could run it through a for loop and set a variable every time you locate the string you're looking for so that the variable gets overwritten every time and you eventually end up with the last instance.

Re: Read a file in reverse-last line first

Posted: 05 Jan 2015 22:57
by foxidrive
This works here:

Code: Select all

@echo off
for /f "delims=:" %%a in ('findstr /n /i "^B22" "dir.dat"') do set "num=%%a"
echo "%num%"
pause

Re: Read a file in reverse-last line first

Posted: 06 Jan 2015 12:05
by Jer
Thankyou both for your comments on a solution.
foxidrive, your solution works perfectly for what I need:
finding the last occurrence of a string in a file of file names
with no spaces, searching at the beginning of the line, and returning the line number.

I also want to know what the file name is. Here is that code:

Code: Select all

@echo off
Set var="^B22"

for /f "tokens=1,2 delims=:" %%a in ('findstr /n /i %var% "dir.dat"') do  set "num=%%a" & set "txt=%%b"

echo Line: "%num%" Text: %txt%
pause