Findstr to read user-defined line from a "for" loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Rileyh
Posts: 147
Joined: 01 Sep 2011 03:54
Location: Perth, Western Australia

Findstr to read user-defined line from a "for" loop

#1 Post by Rileyh » 15 Jan 2012 01:29

SCENARIO:
(in test.txt)

Code: Select all

(empty line)
printline Hello World
(empty line)


(in my current batch file)

Code: Select all

@echo off
setlocal enabledelayedexpansion
:loop
set "$file=test.txt"
for /f "tokens=1-2*" %%a in ('findstr /b /i "printline" "!$file!"') do (
  set command=%%a
  set value=%%b
  echo %%b
  goto :break
  )

:break
(file continues)


THE ISSUE:
After extensive trial and error I have concluded that findstr does not read only the first line, it "picks out" the string from the file test.txt rather than reading line by line.
I need it to read the file on a line that I set (as a variable).

Thanks in advance.
Regards,
Rileyh

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Findstr to read user-defined line from a "for" loop

#2 Post by dbenham » 15 Jan 2012 07:40

:shock: I already answered your identical question at Specify which line to read in "Findstr"
dbenham wrote:

Code: Select all

@echo off
set "$file=test.txt"
set "x=50"
set "command="
set "value="
for /f "tokens=1,2* delims=: " %%a in ('findstr /n /i /b "printline " ^| findstr /b "%x%:"') do (
  set "command=%%b"
  set "value=%%c"
  setlocal enabledelayedexpansion
  echo !value!
  endlocal
)
(file continues)



2 tweaks - no need to keep 1st token, and removed <space> after "printline".

Code: Select all

@echo off
set "$file=test.txt"
set "x=50"
set "command="
set "value="
for /f "tokens=2* delims=: " %%a in ('findstr /n /i /b "printline" ^| findstr /b "%x%:"') do (
  set "command=%%a"
  set "value=%%b"
  setlocal enabledelayedexpansion
  echo !value!
  endlocal
)
(file continues)

Rileyh wrote:After extensive trial and error I have concluded that findstr does not read only the first line, it "picks out" the string from the file test.txt rather than reading line by line.
I need it to read the file on a line that I set (as a variable).

FINDSTR reads every line of test.txt and prints only the lines that match the specified search. That behavior cannot be changed.


Dave Benham

Rileyh
Posts: 147
Joined: 01 Sep 2011 03:54
Location: Perth, Western Australia

Re: Findstr to read user-defined line from a "for" loop

#3 Post by Rileyh » 15 Jan 2012 23:32

I sincerely apologize to both Squashman and dbenham for my poor conduct on this forum. I did not test your code enough dbenham which I have now found out works exactly as I needed it to. I honestly am sorry to you both and I hope that we can get past this.

Apologies,
Rileyh

Post Reply