Read a file in reverse-last line first

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Read a file in reverse-last line first

#1 Post by Jer » 05 Jan 2015 21:55

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.

ShadowThief
Expert
Posts: 1167
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: Read a file in reverse-last line first

#2 Post by ShadowThief » 05 Jan 2015 22:47

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.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Read a file in reverse-last line first

#3 Post by foxidrive » 05 Jan 2015 22:57

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

Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Re: Read a file in reverse-last line first

#4 Post by Jer » 06 Jan 2015 12:05

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

Post Reply