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.
Read a file in reverse-last line first
Moderator: DosItHelp
-
- Expert
- Posts: 1167
- Joined: 06 Sep 2013 21:28
- Location: Virginia, United States
Re: Read a file in reverse-last line first
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
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
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:
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